我创建了这个示例代码,以解释我要做什么。
arr = [
{ id:1 , name:'a', title: 'qmummbw' },
{ id:2 , name:'b', title: 'sdmus' },
{ id:2 , name:'', title: 'dvfv' },
{ id:3 , name:'c', title: 'dujuw' },
{ id:1 , name:'d', title: 'ccnyu' },
{ id:4 , name:'e', title: 'tjtjn' },
{ id:4 , name:'f', title: 'tryr' },
{ id:1 , name:'g', title: 'gbgfbgf' },
{ id:2 , name:'h', title: 'tgrtg' },
{ id:3 , name:'i', title: 'fdvd' },
{ id:1 , name:'j', title: 'dsnyc' },
{ id:1 , name:'k', title: 'nyuny' }
];
array = [];
allArray = [];
for (i = 0; i < arr.length; i++) {
for (j = i + 1; j < arr.length; j++) {
if (arr[i].id === arr[j].id) {
if (!array.includes(arr[i])) {
array.push(arr[i], arr[j]);
} else {
array.push(arr[j]);
}
allArray.push(array);
array = []
}
}
}
console.log(allArray);
我得到的输出是:
[[{
id: 1,
name: "a",
title: "qmummbw"
}, {
id: 1,
name: "d",
title: "ccnyu"
}], [[circular object Object], {
id: 1,
name: "g",
title: "gbgfbgf"
}], [[circular object Object], {
id: 1,
name: "j",
title: "dsnyc"
}], [[circular object Object], {
id: 1,
name: "k",
title: "nyuny"
}], [{
id: 2,
name: "b",
title: "sdmus"
}, {
id: 2,
name: "",
title: "dvfv"
}], [[circular object Object], {
id: 2,
name: "h",
title: "tgrtg"
}], [[circular object Object], [circular object Object]], [{
id: 3,
name: "c",
title: "dujuw"
}, {
id: 3,
name: "i",
title: "fdvd"
}], [[circular object Object], [circular object Object]], [[circular object Object], [circular object Object]], [[circular object Object], [circular object Object]], [{
id: 4,
name: "e",
title: "tjtjn"
}, {
id: 4,
name: "f",
title: "tryr"
}], [[circular object Object], [circular object Object]], [[circular object Object], [circular object Object]], [[circular object Object], [circular object Object]]]
我的主要目标是获取对象数组,每个对象都包含相同的 id 并记住 arr = [] 可以没有数据。
Helenr
月关宝盒
RISEBY
相关分类