How to change value of keys in multiple nested objects at once in JavaScript

61 views Asked by At
let obj = { name : "raj" , age : 23 , second : {
            name : "suraj" , location : "mumbai" } ,
            third : { name : "arjun" , age : 34 , friend : {
            name : "pratik" , status : "married" } } }

If we have objects inside object which have same key name "name" and we want to change value of all that to "nikhil". How can we do it at once. This question ask me in an Interview. How can we do that , if anyone know please let me know.

Just want to change value of all "name" key to "nikhil".

3

There are 3 answers

1
Paulo R. On

const mapKeys = (() => {
  function isObject(obj) {
    return (
      typeof obj === 'object' && !Array.isArray(obj) && obj !== null
    );
  }
  
  function mapKeysWithFn(obj, mapper) {
    if (isObject(obj)) {
      return Object.entries(obj).reduce((result, [key, val]) => {
        result[mapper(key)] = mapKeys(val, mapper);
        return result;
      }, {});
    } else {
      return obj;
    }
  }
  
  function mapKeysWithObj(obj, mapper) {
    return mapKeysWithFn(obj, (key) => {
      return mapper[key] ?? key;
    });
  }
  
  return function mapKeys(obj, mapper) {
    if (typeof mapper === 'function') {
      return mapKeysWithFn(obj, mapper);
    } else {
      return mapKeysWithObj(obj, mapper);
    }
  };
})();

// USAGE
const originalObj = {
  name: 'raj',
  age: 23,
  second: {
    name: 'suraj',
    location: 'mumbai'
  },
  third: {
    name: 'arjun',
    age: 34,
    friend: {
      name: 'pratik',
      status: 'married'
    }
  }
};


// Option 1) Pass a function as the 2nd argument
// that receives they original key. the return value
// becomes the new key.
// Useful for more complicated naming logic
const result1 = mapKeys(originalObj, (key) => {
  if (key.startsWith('na') && key.endsWith('me')) {
    return 'nikhil';
  } else {
    return key;
  }
});

console.log(result1);

// Option 2) Pass an object as the 2nd argument
// if it's a simple key to key mapping
const result2 = mapKeys(originalObj, {
  name: 'nikhil'
});

console.log(result2);

0
Mohit Sharma On

recursion is your friend, you have to traverse to all node recursively and change with value.

remember one thing it will change to original Object.

let obj = { 
  name : "raj" ,
  age : 23 ,
  second :  {
    name : "suraj" ,
    location : "mumbai"
  } ,
  third : { 
    name : "arjun" ,
    age : 34 , 
    friend : {
      name : "pratik" , 
      status : "married",
      arr: [
          {
            name: 'dj',
            obj: 'dj'
          },
          {
            name: '123',
            obj: '123'
          },
          {
            name: '456',
            obj: '456'
          }
        ]
    } 
  } 
}
            
            
function traverse(target, keyToFind, valueToReplace) {
  for (const key in target) {
    if (key !== 'e' && typeof target[key] === 'object') {
      traverse(target[key], keyToFind, valueToReplace);
    } else if (key === keyToFind) {
      target[key] = valueToReplace;
    }
  }
  return target;
}
console.log(traverse(obj, 'name', 'nikhil'));

0
Jay On

As others mentioned this could be done using recursion.

However, if you're looking for a more concise way to achieve the same result, you can use a library like Lodash, which provides utility functions for working with objects and arrays. Here's how you can do it using Lodash:

const _ = require("lodash");

function replaceKey(obj, oldKey, newKey) {
  return _.transform(obj, (result, value, key) => {
    const updatedKey = key === oldKey ? newKey : key;
    result[updatedKey] = _.isObject(value) ? replaceKey(value, oldKey, newKey) : value;
  });
}

let obj = {
  name: "raj",
  age: 23,
  second: {
    name: "suraj",
    location: "mumbai"
  },
  third: {
    name: "arjun",
    age: 34,
    friend: {
      name: "pratik",
      status: "married"
    }
  }
};

let result = replaceKey(obj, "name", "nikhil");

console.log(result);

output:

{
  nikhil: 'raj',
  age: 23,
  second: { nikhil: 'suraj', location: 'mumbai' },
  third: {
    nikhil: 'arjun',
    age: 34,
    friend: { nikhil: 'pratik', status: 'married' }
  }
}

Using Lodash's _.transform and _.isObject functions simplifies the code and makes it more readable. Lodash also has built-in handling for deep traversal and modification of objects, which can be more efficient in certain scenarios.