1

I've got an object and I want to update it with new data. But, if one of the keys has a value of undefined, I want it to have the same value it was priorly defined.

let obj 

obj = {
  name: 'Bill'
  job: 'dev'
  age: 22
}

const newObj = {
  name: 'Sam',
  age: 33
}

Object.keys(obj).forEach(key => {
  obj[key] = newObj[key];
});

I want obj to return:

{
  name: "Sam"
  job:'dev',
  age: 33,

}

But it returns:

{
  age: 33,
  job: undefined,
  name: "Sam"
}

Also, it would help to return in the same order as the original.

3
  • 1
    Check if(key in newObj) before updating Commented May 29, 2020 at 15:00
  • 472 The iteration order for objects follows a certain set of rules since ES2015, but it does not (always) follow the insertion order. Simply put, the iteration order is a combination of the insertion order for strings keys, and ascending order for number-like keys. Commented May 29, 2020 at 15:01
  • @adiga - It could still exist and have the value undefined... Commented May 29, 2020 at 15:01

3 Answers 3

1

You can simply merge the objects using spread syntax like:

let obj 

obj = {
  name: 'Bill',
  job: 'dev',
  age: 22,
}

const newObj = {
  name: 'Sam',
  age: 33,
}

obj= {...obj, ...newObj}
console.log( obj )

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

Comments

0

you can do this:

Object.keys(obj).forEach(key => {
 obj[key] = newObj[key] ? newObj[key] : obj[key];
});

Comments

0
let obj 

obj = {
  name: 'Bill',
  job: 'dev',
  age: 22
}

const newObj = {
  name: 'Sam',
  age: 33
}

obj= {
  ...obj,
  ...newObj
}

Spread will solve your problem. newObject properties will override object properties. (same properties for override)

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.