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/[email protected]"></script>
添加回答
舉報