[英]How to Remove Specific object from arrayList using Javascript or Lodash
I have two objects like this. 我有两个这样的对象。
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'
}];
I want to remove the objects of Result which has matched with all three properties of find object. 我想删除与查找对象的所有三个属性匹配的结果对象。 I want the result should be like this:
我希望结果应该是这样的:
[{
licenseId: '1111',
batchId: 'C123',
name: 'yyy',
tag: 'college',
sem: 'second'
},
{
licenseId: '3456',
batchId: 'B123',
name: 'yyy',
tag: 'college',
sem: 'second'
}];
Can you assist? 你能帮忙吗?
Following code should work. 下面的代码应该工作。
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;
}
}
}
You can use array find method to find if the result array has the matched element. 您可以使用数组查找方法查找结果数组是否具有匹配的元素。 Here
licenseId
is used to find if result array contain the same element. 这里的
licenseId
用于查找结果数组是否包含相同的元素。
If it is found there use index
argument to find it's index. 如果找到,则使用
index
参数查找其索引。 Then use splice
to delete the specific element. 然后使用
splice
删除特定元素。
also you can use array forEach
to loop through the find
array 您也可以使用数组
forEach
遍历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)
I would use remove and some 我会使用删除和一些
_.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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.