1

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) }
2
  • can you also add the "topicArray" code in the post? Commented Nov 28, 2018 at 22:37
  • Don't post images of data, post sample of actual data so it can be run through your code to test and improve on Commented Nov 28, 2018 at 22:38

1 Answer 1

2

One option is to loop through each item, and simply filter() out the non matching modules:

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)

Sign up to request clarification or add additional context in comments.

2 Comments

No worries. Also don't forget to mark answers as correct if you feel they are ;)
emailed you about some freelance work :) would you be interested?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.