Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I overwrite property if exists?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
 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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading