简体   繁体   English

如何将值与嵌套数组中的其他对象进行比较?

[英]How to compare value with other objects in nested array?

How do I compare nested array values with an object in the parent and delete the object if they do not match? 如何将嵌套数组的值与父对象中的对象进行比较,如果不匹配则删除该对象? I need to iterate through the entire array to be left with only "modules" in the child which match the parent "module". 我需要遍历整个数组,以便在子级中只剩下与父级“模块”匹配的“模块”。

Here is the image of the console to see my array structure. 这是控制台的图像,用于查看我的数组结构。

for (var i = topicArray.length - 1; i >= 0; i--) {
if (topicArray[i].module !== module)
topicArray.splice(i, 1) }

One option is to loop through each item, and simply filter() out the non matching modules: 一种选择是遍历每个项目,然后简单地filter()出不匹配的模块:

 const data = [ { module: 'A', topics: [ { topic: 'something', module: 'A' }, { topic: 'something else', module: 'B' } ] }, { module: 'B', topics: [ { topic: 'something', module: 'A' }, { topic: 'something else', module: 'B' } ] } ] data.forEach(item => { item.topics = item.topics.filter(topic => item.module === topic.module) }) console.log(data) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM