skip to Main Content
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

Answers


  1. function isObject( obj ) {
      return typeof obj === 'object' && !Array.isArray(obj) && obj !== null;
    }
    
    function mapKeys( obj, fn ) {
       if ( isObject(obj) ) {
        return Object.entries(obj).reduce( (result, [key, val]) => {
          result[fn(key)] = mapKeys(val, fn)
          return result;
        }, {});
        
      } else {
        return obj;
      }
    }
    
    function mapKeysFromKeysMap( obj, keysMap ) {
      return mapKeys(obj, (key) => {
        return keysMap[key] ?? key;
      });
    }
    
    // Usage
    const originalObj = {
      name : "raj" ,
      age : 23 ,
      second : {
        name : "suraj" ,
        location : "mumbai"
      } ,
      third : {
        name : "arjun" ,
        age : 34 ,
        friend : {
          name : "pratik" ,
          status : "married"
        }
      }
    }
    
    
    const resultObj = mapKeysFromKeysMap(originalObj, {
      'name': 'nikhil'
    });
    
    console.log(resultObj);
    Login or Signup to reply.
  2. 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'));
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search