Цикл по массиву для фильтрации массива объектов - PullRequest
0 голосов
/ 07 апреля 2020

У меня проблемы с поиском пути l oop через элементы массива для фильтрации другого массива объектов. Я нашел способ перебирать this.productID, когда есть только один элемент, но когда this.productID является массивом, элементы отображаются с их содержимым, помеченным как неопределенное.

Спасибо за помощь!

Примечание: productLib передается как product от его родительского компонента

export class Product extends React.Component {
    constructor(props){
        super(props);

        this.productID = this.props.product.similarItems;
        this.filterProductById = this.filterProductById.bind(this);
    }

    filterProductById() {
        return this.productID.map(ID => {
            return productLib.filter(product => {                    
                return product.ID === ID
            })
        })}

        /*
        The code below only works when there's a single string in this.productID
        return productLib.filter(product => {
            return product.ID === this.productID
        })}*/
        
        
    render() {
        return(
            
                <div className="recommended">
                    {
                    this.filterProductById().map(product => {
                        return <Products product={product} key={product.ID}/>
                    })
                    }
                </div>
        )
    }
}

Вот как форматируются данные в productLib:

export const productLib = [
    {
    ID: "001",
    
    ...,
    
    similarItems: ["004", "002", "001", "015"],
    },
    {...},
    ...
]

Ответы [ 3 ]

1 голос
/ 07 апреля 2020

Вы можете использовать функцию includes(), чтобы проверить, содержит ли массив определенный элемент.


Array.prototype.includes ():

Метод include () определяет, включает ли массив определенное значение в свои записи, возвращая в зависимости от ситуации true или false.

Подробнее здесь .


С учетом сказанного вы можете переписать это:

return productLib.filter(product => {
    return product.ID === this.productID
})}

на это:

return productLib.filter(product => {
    return this.productID.includes(product.ID);
})}
0 голосов
/ 07 апреля 2020

Замена возвращение product.ID === this.productID на return this.productID.includes (product.ID) решило мою проблему.

Вот метод filterProductById с поправками:

filterProductById() {
        return productLib.filter(product => {
            return this.productID.includes(product.ID)
})}

- Спасибо @ Ivan86

0 голосов
/ 07 апреля 2020

просто выстрел в темноте, но не должен filterProductById выглядеть следующим образом:


    filterProductById() {
        // iterate through the list of similar ids
        return this.productID.map(ID => {
            // find the corresponding item in the lib
            console.log('searching for an item with ID', ID)
            return productLib.find(product => {
                console.log('found product with ID', ID, product)
                return product.ID === ID
            })
        })
        .filter(Boolean) // filter out undefined items (you can also use reduce to combine all of this)
    }

...