简体   繁体   中英

JavaScript compare, match, and assign object in in nested array

I am having trouble assigning a value from my nested array. The loop is moving through correctly and looks to initially make a comparison of the following arrays.

let searchSource = [ 'media', 'arts'];

let subscriberNodes = [
   {
      name: 'customer',
      nodes: [
         {source: 'media'},
      ]
   }
]

Unfortunately with the code below I am not filtering through the data.

 let violation = subscriberNodes
      .filter( v => v.nodes = v.nodes.filter(q => searchSource === q.source) );

The searchName and q.source compare on one phase of the break point in the debugger but as I click again

 q.source // 'EDW'  to undefined

I am not sure why I am seeing it compare the same values 2 times and why the second time q.source is undefined. It seems like filters are running 2 times.

I tried this with find as well but errored out the same result on the filter

  let qualifierViolations = profilerNodes
        .find(item => item.nodes)
        .filter(value => value.source === smartSearch)

When using .some I found that everything was getting touched but nothing filtered

let qualifierViolations = subscriberNodes
        .filter( v => v.nodes.some(q => searchSource !== q.source) );

At this point I do not know what I am missing or how to fix it. Any insight would be greatly appreciated.

let subscriberNodes = [ { name: 'customer', nodes: [ {source: 'media'}, ] } ]

I'm not sure of what you want to filter out, but if you want to keep only the users that have {source: 'media'} or {source: 'arts'} , here's how you can do it :

 let searchSouce = ['media', 'arts']; let subscriberNodes = [{ name: 'customer1', nodes: [{ source: 'media' }] }, { name: 'customer2', nodes: [{ source: 'arts' }, { source: 'something' }] }, { name: 'customer3', nodes: [{ source: 'something else' }] } ] let violation = subscriberNodes.filter(subscriber => subscriber.nodes.filter(node => searchSouce.indexOf(node.source) !== -1).length ); console.log(violation) // Keeps only customer 1 and 2 

nodes.filter will keep the nodes that contain {source: 'media'} or {source: 'arts'} . So, getting the filtered .length will return 0 or greater, which will in turn decide whether the subscriber is eventually kept or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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