我有一个JSON文件里面的数据。我必须过滤数据:如果用户有两个以上的名字,如果用户id是连续的。JSON文件:
[
{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "mcdonaldholden@xerex.com",
"nameList": [
{
"id": 0,
"name": "Wendi Mooney"
},
{
"id": 2,
"name": "Holloway Whitehead"
}
]
},
{
"_id": "62bd5fbac3e5a4fca5e85e81",
"index": 1,
"nameList": [
{
"id": 0,
"name": "Janine Barrett"
},
{
"id": 1,
"name": "Odonnell Savage"
},
{
"id": 2,
"name": "Patty Owen"
}
]
}, ...
我已经设法找到了一个解决方案来过滤,如果用户有两个以上的名字:userData.filter((names,i) => { return names?.nameList?.filter(names => { return names.name;}).length > 2 ; })
但是我似乎无法理解过滤连续id的概念。我也被建议不要使用任何for循环。只有ES6数组循环,如map, forEach和filter。
下面是使用every()
比较每个元素的ID与前一个ID的解决方案:
const result = data.filter(({nameList}) =>
nameList.length > 2 &&
nameList.every(({id}, i, a) => !i || id === a[i - 1].id + 1)
);
完整的片段:
const data = [{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "mcdonaldholden@xerex.com",
"nameList": [{
"id": 0,
"name": "Wendi Mooney"
}, {
"id": 2,
"name": "Holloway Whitehead"
}]
}, {
"_id": "62bd5fbac3e5a4fca5e85e81",
"index": 1,
"nameList": [{
"id": 0,
"name": "Janine Barrett"
}, {
"id": 1,
"name": "Odonnell Savage"
}, {
"id": 2,
"name": "Patty Owen"
}]
}];
const result = data.filter(({nameList}) =>
nameList.length > 2 &&
nameList.every(({id}, i, a) => !i || id === a[i - 1].id + 1)
);
console.log(result);