我有这样的初始数据:
[
{
"ru":"R401","area":"RFCC","unit":"OFFSITE","tot":1
}, {
"ru":"R401","area":"RFCC","unit":"OFFSITE","tot":1
}, {
"ru":"R401","area":"RFCC","unit":"OFFSITE","tot":1
}, {
"ru":"R401","area":"RFCC","unit":"RCU","tot":1
}
]
如果某些键相同,我想在对象中推送数组,结果变成这样:
[
{
"ru":"R401",
"tot":[1, 1, 1, 1],
"unit":["OFFSITE","OFFSITE","OFFSITE","RCU"]
}
]
然后,如果键“ tot”和“ unit”的对应值相同,但是我的逻辑不好,我想将对象“ tot”和“ unit”分组,然后将其推入新数组。
我希望输出是这样的:
[
{
"ru":"R401",
"tot":[1, 1],
"unit":["OFFSITE","RCU"]
}
]
我该怎么做? 预先感谢。
答案 0 :(得分:4)
假设两个数组的长度相同,则可以使用Set
和两个数组的对应值。
var object = { ru: "R401", tot: [1, 1, 1, 1], unit: ["OFFSITE", "OFFSITE", "OFFSITE", "RCU"] },
unique = new Set,
i = object.tot.length,
json;
while (i--) {
json = JSON.stringify([object.tot[i], object.unit[i]]);
if (unique.has(json)) {
object.tot.splice(i, 1);
object.unit.splice(i, 1);
continue;
}
unique.add(json);
}
console.log(object);
答案 1 :(得分:-1)
正确,使用Set是正确的选择。
我将使其更通用:
const source = [
{
"ru":"R401",
"tot":[1, 1, 1, 1],
"unit":["OFFSITE","OFFSITE","OFFSITE","RCU"]
}];
source.map(el => {
Object.entries(el).forEach( en => {
if(Array.isArray(el[en[0]]))
el[en[0]] = Array.from(new Set(el[en[0]]));
});
});
console.log(source);
是您需要的吗?