2 回答
TA贡献1864条经验 获得超6个赞
map您可以为每个元素和filter每个list元素执行 a
我在这里使用展开运算符来保持其他属性相同,只需修改list
const x = [
{
name: "Peter",
list: [
{ position: "high", id: "ZZ" },
{ position: "low", id: "KJ" },
],
},
{
name: "Alise",
list: [
{ position: "high", id: "TC" },
{ position: "low", id: "ZZ" },
],
},
];
const res = x.map((el) => ({
...el,
list: el.list.filter(({ id }) => id !== "ZZ"),
}));
console.log(res);
TA贡献2012条经验 获得超12个赞
// const objectScan = require('object-scan');
const myData = [ { name: 'Peter', list: [{ position: 'high', id: 'ZZ' }, { position: 'low', id: 'KJ' }] }, { name: 'Alise', list: [{ position: 'high', id: 'TC' }, { position: 'low', id: 'ZZ' }] } ];
const prune = (data, id) => objectScan(['[*].list[*]'], {
rtn: 'count',
filterFn: ({ value, property, parent }) => {
if (value.id === id) {
parent.splice(property, 1);
return true;
}
return false;
}
})(data);
console.log(prune(myData, 'ZZ')); // returns the number of deletions
// => 2
console.log(myData);
// => [ { name: 'Peter', list: [ { position: 'low', id: 'KJ' } ] }, { name: 'Alise', list: [ { position: 'high', id: 'TC' } ] } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>
添加回答
举报