亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從嵌套 json 中過濾項目

從嵌套 json 中過濾項目

一只甜甜圈 2023-11-12 14:59:37
有一個json:x = [{"name":"Peter", "list":[{"position":"high", "id":"ZZ"},                         {"position":"low", "id":"KJ"}]},{"name":"Alise", "list":[{"position":"high", "id":"TC"},                         {"position":"low", "id":"ZZ"}]}]我需要使用filter()刪除“list”中包含“id”:“ZZ”的那些項目。我期望最終的結果如下:[{"name":"Peter", "list":[{"position":"low", "id":"KJ"}]},{"name":"Alise", "list":[{"position":"low", "id":"ZZ"}]}]我嘗試實現這一目標:y = for (i=0;i<x.length;++i){        for (n=0;n<x[i]["list"].length;++n){             x[i]["list"][n].filter(id => "id" == "ZZ")        }    }瀏覽器控制臺輸出顯示Uncaught TypeError: x[i]["list"][n].filter is not a function.你能告訴我如何過濾給定的 json 并擺脫 "id":"ZZ" 行嗎?
查看完整描述

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);


查看完整回答
反對 回復 2023-11-12
?
繁花如伊

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>


查看完整回答
反對 回復 2023-11-12
  • 2 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號