Assigning an object extends an immutable object array

I want to have an immutable source array of an object and expand it, but it seems the code below did the correct result. obj3 became an object instead of an array of an object. I even tried to expand lodash.

var obj1 = [{
  abc: 'abc value'
}, {
  def: 'def value'
}];

var obj2 = {
  def: 'new def value'
};

/*var obj3 = _.extend({}, obj1, obj2);
console.log(obj3)
*/

var obj3 = Object.assign({},obj1,obj2);

https://jsbin.com/bawadeqicu/edit?html,js,output

Out of my desire

obj1: [{"abc":"abc value"},{"def":"def value"}] // immutable
obj3: [{"abc":"abc value"},{"def":"new def value"}]
+4
source share
2 answers

You can use the .map()distribution element with the parameter obj1passed in Object.assign()to distribute the elements of the array object obj1to a new array.

var obj1 = [{
  abc: 'abc value'
}, {
  def: 'def value'
}];

var obj2 = {
  def: 'new def value'
};

var obj3 = Object.entries(Object.assign({},...obj1, obj2))
           .map(([prop, value]) => ({[prop]:value}));

console.log(
  `obj1:${JSON.stringify(obj1)}`
  , `\nobj2:${JSON.stringify(obj2)}`
  , `\nobj3:${JSON.stringify(obj3)}`
)
Run codeHide result
+2
source

Transition is immutable

, , :

const person = {
  name: 'John',
  age: 28
}
const newPerson = Object.assign({}, person, {
  age: 30
})
console.log(newPerson === person) // false
console.log(person) // { name: 'John', age: 28 }
console.log(newPerson) // { name: 'John', age: 30 }

+1

Source: https://habr.com/ru/post/1666052/


All Articles