如何使用Javascript或Lodash从arrayList中删除特定对象
问题描述:
我有两个这样的对象。如何使用Javascript或Lodash从arrayList中删除特定对象
var find = [{
licenseId: 'A123',
batchId: '123',
name: 'xxx'
},
{
licenseId: 'B123',
batchId: '124',
name: 'yyy'
}];
var result = [
{
licenseId: 'A123',
batchId: '123',
name: 'xxx',
tag: 'college',
sem: 'fourth'
},
{
licenseId: 'B123',
batchId: '124',
name: 'yyy',
tag: 'college',
sem: 'third'
},
{
licenseId: '1111',
batchId: 'C123',
name: 'yyy',
tag: 'college',
sem: 'second'
},
{
licenseId: '3456',
batchId: 'B123',
name: 'yyy',
tag: 'college',
sem: 'second'
}];
我想删除结果已与所有三个属性匹配找到对象的对象。我想要的结果应该是这样的:
[{
licenseId: '1111',
batchId: 'C123',
name: 'yyy',
tag: 'college',
sem: 'second'
},
{
licenseId: '3456',
batchId: 'B123',
name: 'yyy',
tag: 'college',
sem: 'second'
}];
你能协助吗?
答
以下代码应该可以工作。
for(var j=0;j < find.length;j++){
for (var i = 0; i < result.length; i++) {
if ((result[i].licenseId == find[j].licenseId) &&
(result[i].name == find[j].name) &&
(result[j].batchId == find[j].batchId)) {
result.splice(i, 1);
break;
}
}
}
答
可使用数组find方法找到,如果结果数组有匹配的元素。这里使用licenseId
来查找结果数组是否包含相同的元素。
如果发现使用index
参数找到它的索引。然后使用splice
删除特定元素。
,你也可以通过find
阵列
var find = [// json objects];
var result = [// json objects];
find.forEach(function(item){
var _findInResult = result.find(function(itemInResult,index){
if(itemInResult.licenseId == item.licenseId){
result.splice(index,1);
}
return itemInResult.licenseId == item.licenseId
})
})
console.log(result)
答
_.remove(result, function(obj) {
return _.some(find, {
licenseId: obj.licenseId,
batchId: obj.batchId,
name: obj.name,
});
});
var find = [{
licenseId: 'A123',
batchId: '123',
name: 'xxx'
},
{
licenseId: 'B123',
batchId: '124',
name: 'yyy'
}];
var result = [
{
licenseId: 'A123',
batchId: '123',
name: 'xxx',
tag: 'college',
sem: 'fourth'
},
{
licenseId: 'B123',
batchId: '124',
name: 'yyy',
tag: 'college',
sem: 'third'
},
{
licenseId: '1111',
batchId: 'C123',
name: 'yyy',
tag: 'college',
sem: 'second'
},
{
licenseId: '3456',
batchId: 'B123',
name: 'yyy',
tag: 'college',
sem: 'second'
}];
_.remove(result, function(obj) {
return _.some(find, {
licenseId: obj.licenseId,
batchId: obj.batchId,
name: obj.name,
});
});
console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.15.0/lodash.min.js"></script>
请张贴你的努力 – mplungjan
你确定多么希望最终结果看起来像吗?我的意思是你拿一个licenseId并把它作为一个batchId。最终的结果是,你有一个3456的licenseId,但是这在起始数组中并不存在。 –