How to achive this result :
const defaultValues = { a:1, b:1 , c:1};// All acceptable properties
const overrideValues = { a:2, x: 3, y: 3, z:3 };// from user
const values = ? ;//
console.log(values);
// output:
// Object { a: 2, b: 1, c: 1 }
Thxs,
Post-Edit : Thank you all for your precious help. (I read the duplicate question: Update javascript object with another object, but only existing keys)
However, I still offer you my solution :
const overrideValues = { a:2, x: 3, y: 3, z:3 };
const defaultValues = {
a: overrideValues.a || 1,
b: overrideValues.b || 1,
c: overrideValues.c || 1
};
const values = defaultValues ;// !
console.log(values);
// output:
// Object { a: 2, b: 1, c: 1 }
You can map over the entries of the default values and set the value to the value in overrideValues for each key that exists on that object.
const defaultValues = { a:1, b:1 , c:1};
const overrideValues = { a:2, x: 3, y: 3, z:3 };
const values = Object.fromEntries(Object.entries(defaultValues)
.map(([k,v])=>[k, overrideValues.hasOwnProperty(k) ? overrideValues[k] : v]));
console.log(values);
You can use spread syntax:
const defaultValues = { a:1, b:1 , c:1};// All acceptable values
const overrideValues = { a:2, x: 3, y: 3, z:3 };
const values = {...defaultValues, ...overrideValues};
console.log(values);
Spread syntax allows you to destructure an object or array, and you can use that restructuring to have default values. If there are multiple instances of a key/value pair, then the second value seen for that key is used, allowing you to override the defaults.