0

Assuming I have the following two objects

foo = {
  a: 10
  b: 'hello'
  c: 'world'
}

bar = {
  a:5
  b: null
  c: null
  d: "This is not in foo"
}

I would like to have an operation which would do the equivalent of below operation but without having to specify it for each member.

  bar.a ??= foo.a
  bar.b ??= foo.b
  bar.c ??= foo.c

  console.log(bar) // {a:5, b:'hello', c:'world', d:'This is not in foo'

Essentially: For each member of bar, if it is nullish take the value in foo. Leave all members which exist in foo but not in bar in peace

How would I go about this? I have tried to search a solution using destructuring in some way but with no success...

2 Answers 2

2

Loop over the keys in foo then perform the assignment operation in the loop.

Object.keys(bar).forEach(k => bar[k] ??= foo[k]);
Sign up to request clarification or add additional context in comments.

6 Comments

derpischer in their solution mentioned that if bar has some undefined properties, they would not be overwritten, is this also the case in your spread syntax solution?
No, it only replaces properties that don't exist at all. I've removed that from the answer.
Should it not be Object.keys(bar)...?
Yes, when I started writing the answer I had the relationship backwards, and didn't fix it properly.
I am actually using typescript and am getting some problems when trying to implement your solution. I have posted a related question about it here: stackoverflow.com/questions/74465046/…
|
0

If you can create a new object instead of manipulating bar you could do as follows

let newbar = Object.assign({}, foo, bar); 

Ie, in the Object.assign it will first assign all properties from foo and then all properties from bar, so properties not existing in bar will be taken from foo and properties existing in bar will be taken from bar.

Be aware, that if bar has an undefined property, this will overwrite the value from foo. So

let bar = { a: undefined }
let foo = { a: 3 }
let combined = Object.assign({}, foo, bar);  
// will result in { a: undefined }

Also be aware, that this will add any property, that exists in foo to the result. So

 let bar = { a: 3 }
 let foo = { b: 4 }
 let combined = Object.assign({}, foo, bar);  
 // will result in { a: 3, b: 4 } 

Not sure if this fits your requirement. If not, go with Barmar's solution.

2 Comments

How could I avoid the undefined problem?
-1, this does not solve the problem: “For each member of bar, if it is nullish take the value in foo”. Your proposal keep nullish values from bar into the resulting object.

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.