简体   繁体   English

使用lodash比较和删除数组中的对象

[英]Using lodash to compare and remove an object from an array

I'm trying to use lodash to compare two arrays of objects and return the difference between the two, then adding it to the original data set. 我正在尝试使用lodash比较对象的两个数组并返回两者之间的差,然后将其添加到原始数据集中。 Reason being, the new data will contain the same data from the original. 原因是,新数据将包含与原始数据相同的数据。 For example, I have 3 objects in orgData , and when I request newData , it will contain the same orgData plus one more object. 例如,我在orgData有3个对象,当我请求newData ,它将包含相同的orgData和一个以上的对象。

var orgData = [{
  "id": 1000,
  "title": "First item"
}, {
  "id": 1001,
  "title": "Second item"
}];

var newData = [{
  "id": 1000,
  "title": "First item"
}, {
  "id": 1001,
  "title": "Second item"
}, {
  "id": 1002,
  "title": "Third item"
}];

My only delimiter in comparing is the id which is unique. 我唯一比较的分隔符是唯一的id I've tried the following, but the error I receive is 'Cannot read property of 'id' undefined' which makes sense. 我尝试了以下操作,但是收到的错误是“无法读取'id'undefined的属性”,这很有意义。

_.filter(orgData, function(o, x) {
  return o.id !== newData[x].id;
}).forEach(function(x) {
  orgData.push(x);
});

Keep track of ids in a separate data structure: 在单独的数据结构中跟踪ID:

var orgDataIds = [];

_.each(orgData, function(value) {
    orgDataIds.push(value.id);
})

Inspect the id of each object in newData, and add the object to orgData when the corresponding id isn't found in the ids array: 检查newData中每个对象的ID,然后在ids数组中找不到对应的ID时,将该对象添加到orgData中:

_.each(newData, function(value) {
    var id = value.id;
    if (orgDataIds.indexOf(id) === -1) {
        orgDataIds.push(id);
        orgData.push(value);
    }
})

It's not clear to me when you want to remove objects from an array though. 但是,当您要从数组中删除对象时,对我来说还不清楚。 Are you intending to take the intersection of the two arrays? 您打算采用两个数组的交集吗?

var orgData = [{ "id": 1000, "title": "First item" }, { "id": 1001, "title": "Second item" }]; var orgData = [{{“ id”:1000,“ title”:“第一项”},{“ id”:1001,“ title”:“第二项”}];

var newData = [{ "id": 1000, "title": "First item" }, { "id": 1001, "title": "Second item" }, { "id": 1002, "title": "Third item" }, { "id": 1003, "title": "Forth item" }]; var newData = [{“ id”:1000,“ title”:“第一项”},{“ id”:1001,“ title”:“第二项”},{“ id”:1002,“ title”:“第三项“},{” id“:1003,” title“:”第四项“}];

var newArray = _.union(orgData,newDate) var newArray = _.union(orgData,newDate)

console.log(JSON.stringify(newArray)) // this will return union of this two array console.log(JSON.stringify(newArray))//这将返回这两个数组的并集

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM