what would be the result of my code ? I am expecting to have as result one single array of length 1 , I want to output only values of d variable that haven't been updated in my var2 variable but I get an array of length 2 , I want to have output
{name : "david", age : 23, day : 23}
const d = [{name : '',age : '',day :23}]
const var2 = [...d, { name : 'david', age : 22}]
console.log(var2)
You are not using the spread operator correctly. You should use it to merge all elements of d[0] with an object containing your updated values.
const d = [{name : '',age : '',day :23}]
// for d containing only one element
const var2 = [{...d[0], name : 'david', age : 22}]
// will result in [{name: '', age: '', day: 23, name: 'david', age: 22}] and be merged by keeping the right-most value
// for all elements in d
const var3 = d.map(el => {
return {...el, name : 'david', age : 22}
})
console.log(var2)
console.log(var3)
Think of it this way:
d is an array of objects
{ name : 'david', age : 22} is an object literal
When you use the spread operator on d, you are telling it to take each object in d and place it into var2, then at the end, append the { name : 'david', age : 22}.
So the result would be an array with all the items you had in d + the object literal { name : 'david', age : 22}.
To get your expected result {name : "david", age : 23, day : 23} merge two objects like shown below.
merge Object like {...object1, ...object2}
const d = [{name : '',age : '',day :23}]
const var2 = {...d[0], ...{ name : 'david', age : 22}}
console.log(var2)