2

I have JSON object

{a : 'vala' , b:'valb' , childval : { x : 'valx'} } another object as {c: 'valc'}

I would like to add these two objects as

{a : 'vala' , b:'valb' , childval : { x : 'valx'} , {c: 'valc'} }

Any pointers on how to add another object.

3
  • Is the first object actually JSON or a JavaScript object? The syntax you posted isn't valid JSON. Also, for childval, do you want to combine all keys into a single object or create an array of objects? Pointers - consider Object.prototype.keys or Object.prototype.entries. Commented Jul 31, 2020 at 4:27
  • 2
    {a : 'vala' , b:'valb' , childval : { x : 'valx'} , {c: 'valc'} } is not a valid syntax, do you mean {a : 'vala' , b:'valb' , childval : { x : 'valx', c: 'valc' } } ? Commented Jul 31, 2020 at 4:29
  • Thanks for pointing it out. I was not thinking about valid JSON. No wonder I was struggling to make it work. Commented Jul 31, 2020 at 5:07

2 Answers 2

3

I would do below if I imagine well your typo:

const foo = { a: 'vala', b: 'valb', childval : { x : 'valx' } };
const bar = { c: 'valc' };

foo.childval = { ...foo.childval, ...bar };

spread syntax is neat for these situations

Sign up to request clarification or add additional context in comments.

Comments

2

Try this

let obj1 = {a : 'vala' , b:'valb' , childval : { x : 'valx'} }
let obj2 = {c: 'valc'};

Object.assign(obj1.childval, obj2);
console.log(obj1);

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.