skip to Main Content

I have one nested JavaScript object and I want to add new key value in each nested object. So basically I have to create custom function to adding it.

**My Input Object:
**

const obj = {
    name: {
        final: {
            val: 'yes'
        }
    }
}

**Expected Object:
**

const outObj = {
    id: 1,
    name: {
        id: 1,
        final: {
            id: 1,
            val: 'yes'
        }
    }
}

2

Answers


  1. You can recursive function and reduce to get the output:

    const obj = {
      name: {
        final: {
          val: 'yes'
        }
      }
    };
    const addId = (obj, id = 1) => Object.entries(obj).reduce((acc, [key, val]) => {
        acc.id = id;
        acc[key] = (typeof val === 'object' && val !== null) ? addId(val, id ) : val;
        return acc;
    }, {});
    
    
    
    const outObj = addId(obj);
    
    console.log(outObj)
    Login or Signup to reply.
  2. The solution is basic recursion. You figure out if any properties of the object is an object and you loop over that one and so on.

    const obj = {
      name: {
        final: {
          val: 'yes'
        }
      }
    }
    
    const obj2 = {
      name: {
        final: {
          val: 'yes',
          age: 22,
          address: {
            city: 'Noida',
            age: 23
          }
        },
        age: 18
      },
      age: 20
    }
    
    
    const addKey = (obj, key, value) => {
      Object.values(obj).forEach(val => {
        if (val && typeof val === 'object') addKey(val, key, value);
      });
      obj[key] = value;
    }
    
    addKey(obj, 'id', 1);
    addKey(obj2, 'id', 2);
    
    console.log(obj);
    console.log(obj2);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search