Irrech
Irrech

Reputation: 1404

Lodash merge object with nested array not working correctly

I found unexpected result when try to merge with lodash object with flat array inside. Here the example:

var people = { name: 'Andrew', age: '30', values: ["PT", "PORTA 31"] };

const person = { age: '31', values: ["PT"] };

var people2 = { name: 'Andrew', age: '30', values: [{ pippo : 1}] };

const person2 = { age: '31', values: [{ pippo : 2}] };

// Now merge person back into people array
console.log(_.merge({}, people, person));

console.log(_.merge({}, people2, person2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

The result of first console.log is

{
  age: "31",
  name: "Andrew",
  values: ["PT", "PORTA 31"]
}

And not as expected

{
  age: "31",
  name: "Andrew",
  values: ["PT"]
}

Someone can explain me why and give me a solution to make sure that with a flat array it takes me the correct value

Upvotes: 1

Views: 2350

Answers (2)

user9757842
user9757842

Reputation:

I think assign is better in this case than merge

This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.

var people = { name: 'Andrew', age: '30', values: ["PT", "PORTA 31"] };

const person = { age: '31', values: ["PT"] };

console.log(_.assign({}, people, person));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Upvotes: 1

Farhad Khan
Farhad Khan

Reputation: 139

I believe _.assign(people, person) would produce the desired outcome in this case https://lodash.com/docs/4.17.15#assign

This functionality is also native and can be used like this Object.assign(target, source)

Upvotes: 0

Related Questions