[英]How to update values not present in one array of objects from another array of objects?
I have two arrays of objects which contain a huge amount of data. 我有两个包含大量数据的对象数组。 The structure of these two arrays goes something like this.
这两个数组的结构类似这样。
arr1 = [
{x: 1, y: '2018-01-01'},
{x: 2, y: '2018-01-02'},
{x: 3, y: '2018-01-03'},
{x: 5, y: '2018-01-05'},
....
]
arr2 = [
{x: 1, y: '2018-01-01'},
{x: 2, y: '2018-01-02'},
{x: 3, y: '2018-01-03'},
{x: 4, y: '2018-01-04'},
{x: 5, y: '2018-01-05'},
{x: 6, y: '2018-01-08'}
]
I want to update arr2
in such a way that it updates the array of objects with values that are only present in arr1 and drop any values not present in arr1. 我要更新
arr2
,使其使用仅出现在arr1中的值更新对象数组,并删除任何不在arr1中的值。 Note, I want to update the original arr2 and not return a new array. 注意,我想更新原始的arr2而不返回新的数组。
I tried iterating through individual arrays and remove values not present but not luck. 我尝试遍历单个数组并删除不存在但不走运的值。
You could get a map and iterate from the end for splicing unknown items or update changed values. 您可以获得一张地图,并从头开始进行迭代以拼接未知项或更新更改后的值。
var arr1 = [{ x: 1, y: '2018-01-01x' }, { x: 2, y: '2018-01-02' }, { x: 3, y: '2018-01-03' }, { x: 5, y: '2018-01-05' }], arr2 = [{ x: 1, y: '2018-01-01' }, { x: 2, y: '2018-01-02' }, { x: 3, y: '2018-01-03' }, { x: 4, y: '2018-01-04' }, { x: 5, y: '2018-01-05' }, { x: 6, y: '2018-01-08' }], map = arr1.reduce((m, { x, y }) => m.set(x, y), new Map), i = arr2.length; while (i--) { if (map.has(arr2[i].x)) { if (map.get(arr2[i].x) !== arr2[i].y) { arr2[i].y = map.get(arr2[i].x); } } else { arr2.splice(i, 1); } } console.log(arr2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.