Reputation: 1518
i am having two array of objects like this
let array1 = [{
id:1,
colorCode:2
}]
let array2 = [{
id:1,
value:3
}]
Here what i want to achieve is . I need to compare this two arrays and their id's are same.I need to change the colorCode
value depends upon the value
. Pls help me to achieve this.Thanks in advance
Upvotes: 0
Views: 95
Reputation: 193258
Create a function using _.flow()
. The function concats the arrays, _.groupBy()
the key (id
), and then _.map()
the groups, and _.merge()
each group:
const { flow, concat, groupBy, map, merge } = _;
const combineBy = key => flow(
concat,
arr => groupBy(arr, key),
groups => map(groups, g => merge({}, ...g))
)
const array1 = [{ id:1, colorCode:2},{id:2, colorCode:2}];
const array2 = [{ id:1, value:3},{id:2, value:4}];
const combineById = combineBy('id');
const result = combineById(array1, array2);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
The same idea is even simpler with lodash/fp. Just replace _.merge()
with _.mergeAll()
:
const { flow, concat, groupBy, map, mergeAll } = _;
const combineBy = key => flow(concat, groupBy(key), map(mergeAll))
const array1 = [{ id:1, colorCode:2},{id:2, colorCode:2}];
const array2 = [{ id:1, value:3},{id:2, value:4}];
const combineById = combineBy('id');
const result = combineById(array1, array2);
console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
Upvotes: 0
Reputation: 17610
U can use mapping
var array1 = [{ id:1, colorCode:2},{id:2, colorCode:2}];
let array2 = [{ id:1, value:3},{id:2, value:4}];
var arr=[];
array1.map(id =>
arr.push({id:id.id,colorCode: array2.find(o => o.id === id.id).value})
);
console.log(arr);
Upvotes: 2