从嵌套 json 中过滤项目

有一个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" 行吗?


一只甜甜圈
浏览 110回答 2
2回答

慕尼黑的夜晚无繁华

map您可以为每个元素和filter每个list元素执行 a我在这里使用展开运算符来保持其他属性相同,只需修改listconst x = [&nbsp; {&nbsp; &nbsp; name: "Peter",&nbsp; &nbsp; list: [&nbsp; &nbsp; &nbsp; { position: "high", id: "ZZ" },&nbsp; &nbsp; &nbsp; { position: "low", id: "KJ" },&nbsp; &nbsp; ],&nbsp; },&nbsp; {&nbsp; &nbsp; name: "Alise",&nbsp; &nbsp; list: [&nbsp; &nbsp; &nbsp; { position: "high", id: "TC" },&nbsp; &nbsp; &nbsp; { position: "low", id: "ZZ" },&nbsp; &nbsp; ],&nbsp; },];const res = x.map((el) => ({&nbsp; ...el,&nbsp; list: el.list.filter(({ id }) => id !== "ZZ"),}));console.log(res);

繁花如伊

// 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// => 2console.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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript