Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

javascript - Nested array of objects filtering returns undefined in JS

I am trying for each product check if tags array of objects has at least one tag of shows.

const allProducts = this.products.forEach(product =>
        product.tags.some(item => item.tagName !== 'shows'),
      )

Data sample:

    Products: [
    {
    productId:...
    productName: ...
    tags:[
    {
    tagId:...
    tagName:...
    }
    {
    tagId:...
    tagName:...
    }
    ]
    },
    {
    productId:...
    productName: ...
    tags:[
    {
    tagId:...
    tagName:...
    }
    {
    tagId:...
    tagName:...
    }
    ]
    }

]

It seems after some() it doesn't work. What is wrong and how can be it fixed?

question from:https://stackoverflow.com/questions/65935319/nested-array-of-objects-filtering-returns-undefined-in-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Firstly, forEach does not return anything. So you should use .filter instead.

for each product check if the tags array of objects has at least one tag of shows.

Secondly, the condition should be === instead of !==, Besides, need return the true if all products are passing the some() not filter

==> Solution:

const allValidProducts = this.products.filter(product => product.tags.some(item => item.tagName === 'shows'));
const result =  allValidProducts.length === this.products.length;  

So as you can see, the .some works fine.

const array = [1, 2, 3, 4, 5];
console.log(array.some(element => element % 2 === 0));
// expected output: true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...