返回比较 Javascript 时存在于两个数组中的对象的索引
Return the index of object that exist in both array when comparing Javascript
------已编辑---------------
我有 2 个对象数组 A、B
var a = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var b = [{id:1},{id:2},{id:3}];
我想删除同时在 A 和 B 中的对象
//after the operation
a = [{id:1},{id:2},{id:3}];
我想为了做到这一点,我需要在 A 中获取它们的索引以使用 A.splice((,但我就是无法弄清楚我该怎么做。
这是我用来从中获取对象本身的代码JavaScript 中两个对象数组之间的区别
var onlyInA = A.filter(function(current){
return res.nodes.filter(function(current_b){
return current_b._id == current._id
}).length == 0
过滤器
中的过滤器不是要走的路。你想使用过滤器和一些。
var a = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var b = [{id:1},{id:2},{id:5},{id:6},{id:7}];
var result = a.filter( function(oa) {
return b.some( function(ob){
return oa.id===ob.id;
});
});
a.length = 0;
a.push.apply(a, result);
console.log(JSON.stringify(a));
如果你想使用 splice((,那么向后循环它。
var a = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var b = [{id:1},{id:2},{id:5},{id:6},{id:7}];
for (var i=a.length-1;i>=0;i--) {
var inB = b.some( function(ob){
return a[i].id===ob.id;
});
if(!inB) {
a.splice(i,1)
}
}
console.log(a);
您可以使用哈希表作为对象的 id,并使用它过滤a
。
var a = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],
b = [{ id: 1 }, { id: 2 }, { id: 3 }],
hash = Object.create(null);
b.forEach(function (item) {
hash[item.id] = true;
});
a = a.filter(function (item) {
return hash[item.id];
});
console.log(a);
相关文章:
- 在JavaScript中通过索引从对象数组中获取值
- Javascript:根据对象的嵌套数组中的值,在数组中查找对象的索引
- “未定义的索引:itemdetails”,当将JSON对象从JavaScript发送到PHP时
- 在知道对象值的情况下,确定数组中JS对象的索引
- 索引IndexedDB中对象中的数组值
- 对象中的索引错误
- 按键查找数组中对象的索引
- 使用Handlebars获取同级JSON数据,其中单个对象没有父索引键,但多个项有一个索引键
- AngularJS - ng-repeat,更新尚未定义的模型对象索引
- 来自 jsp 和 javascript 中的请求属性的对象索引数组
- 使用变量作为对象索引
- 如何使用 JavaScript 获取对象索引值的 JSON 响应
- NamedNodeMap对象内部的Attr对象索引问题
- 使用json中的id查找对象索引
- JSON获取对象索引
- 生成对象而不是对象索引的Javascript for循环
- jQuery对象索引忽略jQuery.filter()
- 确定特定字符串的对象索引
- Angularjs访问对象索引
- 按字符串查找对象索引