2

I want to add a key/value pair inside an object. My object looks like this:

obj = {
   obj1: {
      a: 1,
      b:2,
      c:3
    },
    obj2:{
      a: 1,
      b:2,
      c:3
    },
    obj3:{
      a: 1,
      b:2,
      c:3
    }
}

Now above every sub-objects, I want to add a key/value pair, say: d:4 and it should look like:

 obj = {
   obj1: {
      a: 1,
      b:2,
      c:3,
      d:4
    },
    obj2:{
      a: 1,
      b:2,
      c:3,
      d:4
    },
    obj3:{
      a: 1,
      b:2,
      c:3,
      d:4
    }
}

2 Answers 2

2

one line:

Object.getOwnPropertyNames(obj).forEach(p => obj[p].d = 4);
Sign up to request clarification or add additional context in comments.

1 Comment

Object.getOwnPropertyNames() is the way.
2

This will do it:

for (var o in obj) {
  if (obj.hasOwnProperty(o)) {
    obj[o]['d'] = 4;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.