-3

Say I have object as follows:

let newObject = {
 foo: 'foo-value',
 bar: 'bar-value', 
 baz: 'baz-value'
};

I have also a list:

let list = ['foo', 'baz']

I want to overwrite 'foo-value' and 'baz-value' (value of keys that appear in the list) with some 'default-value'. So I have:

{
 foo: 'default-value',
 bar: 'bar-value', 
 baz: 'default-value'
};

If I have a different object, let's say

let differentObject = {
 x: 'x-value',
 y: 'y-value'
}

I don't want to add any default value so spread operator didn't work for me.

Moortan
  • 1
  • 2

1 Answers1

0

You can achieve that like this

let newObject = {
 foo: 'foo-value',
 bar: 'bar-value', 
 baz: 'baz-value'
};

let list = ['foo', 'baz'];

list.forEach(item => {
  if(newObject[item])
   newObject[item] = 'Default value';
})

console.log(newObject);
0stone0
  • 34,288
  • 4
  • 39
  • 64
sazzad
  • 505
  • 4
  • 5
  • Where is the check that the property exists? I only see a check that the resolved property value is truthy. This is also problematic because it creates new properties if they were only inherited before. – Sebastian Simon Mar 01 '22 at 11:05
  • @SebastianSimon `if(newObject[item])` checks both of them – sazzad Mar 01 '22 at 11:08
  • So it’s not what is being asked for, then. This simply _fails_ for ``let newObject = { foo: "", bar: 0, baz: false }; Object.prototype.inherited = "this property does not exist on `newObject`."; let list = [ "foo", "bar", "baz", "inherited" ];``. – Sebastian Simon Mar 01 '22 at 11:14