我有2个阵列如下。
我想保持" id"阵列2中不存在数组1。
阵列1
{"list":{"0":{"category":"Cat fr 1","list":{"0":{"id":123123123123},"1":{"id":123123123123}
数组2
{"list":{"0":{"category":"Cat fr 1","list":{"0":{"id":123123123123},"1":{"id":123123123123},"1":{"category":"Cat fr 2","list":{"0":{"id":123123123123},"1":{"id":123123123123},"2":{"category":"Cat fr 3","list":{"0":{"id":123123123123},"1":{"id":123123123123}
结果
{"list":{"1":{"category":"Cat fr 2","list":{"0":{"id":123123123123},"1":{"id":123123123123},"2":{"category":"Cat fr 3","list":{"0":{"id":123123123123},"1":{"id":123123123123}
答案 0 :(得分:0)
您可以将filter()
array2与findIndex()
组合成一个新数组(或返回到array2或array1)。
let array1 = [ {
"id": 1,
"name": "one"
}, {
"id": 2,
"name": "two"
} ];
let array2 = [ {
"id": 1,
"name": "one"
}, {
"id": 2,
"name": "two"
}, {
"id": 3,
"name": "three"
}, {
"id": 4,
"name": "four"
} ];
let newArray = array2.filter( ( item ) => {
return array1.findIndex( ( _item ) => item.id == _item.id ) == -1;
} );
console.table( newArray );
// logs: [ { id: 3, name: "three" }, { id: 4, name: "four" } ]
我认为你可以将它应用于你的数组。
更多解释:
filter()
遍历数组中的所有项,并返回一个新数组,其中的对象通过了我们的过滤条件。因此,您需要在它之前声明一个新数组,以便将它放在某处。 let newArray = ...
findIndex()
返回与indexOf()
类似的索引,但您可以为其指定条件。在这个例子中,它返回对象的索引,该对象的id与我们正在过滤的数组中的项的id相同。 item.id == _item.id
当它找不到任何此类对象时,它将返回-1
。您希望将返回-1
的对象放入新数组中。您想要将它们“过滤”到新数组中。这就是我们检查它的原因:... == -1
。
答案 1 :(得分:0)
var array1=jQuery.parseJSON('{"list":{"0":{"category":"Cat fr 1","list":{"0":{"id":123123123123},"1":{"id":123123123123}}}}}');
var array2=jQuery.parseJSON('{"list":{"0":{"category":"Cat fr 1","list":{"0":{"id":123123123123},"1":{"id":123123123123}}},"1":{"category":"Cat fr 2","list":{"0":{"id":123123123123},"1":{"id":123123123123}}},"2":{"category":"Cat fr 3","list":{"0":{"id":123123123123},"1":{"id":123123123123}}}}}');
var list1=array1["list"];
var list2=array2["list"];
var checkArray=[];
var result={};
for (var key in list1) {
if (list1.hasOwnProperty(key)) {
var val = list1[key];
checkArray.push(val["category"]);
}
}
for (var key in list2) {
if (list2.hasOwnProperty(key)) {
var val = list2[key];
if(!checkArray.includes(val["category"]))
{
result[key]=val;
}
}
}
var finalResult={};
finalResult["list"]=result;
console.log(JSON.stringify(finalResult));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;