Search code examples
javascriptreact-nativeecmascript-5

How to filter object in one array using propery in another in javascript?


First Array

const firstArray = [
{
   "value": "306",
   "label": "All"
},
{
   "value": "316",
   "label": "Tips"
},
{
   "value": "315",
   "label": "News"
},
{
   "value": "32",
   "label": "Jobs"
}]

Second Array

const secondArray = [
{
   name: "name",
   description: "desc",
   image: "path_image",
   culture: [{
     name: "name",
     value: "32"
   }]
},
{
   name: "name",
   description: "desc",
   image: "path_image",
   culture: [{
     name: "name",
     value: "32"
   }]
}];

Trying to filter my firstArray with only keeping the object with the value corresponding to 32.

Still learning Javascript and it's in a React Native Project. They changed some info of the API and it was working when I only had : culture":"32"

Code :

let newOrigin = [...new Set(this.state.secondArray.map(product => product.culture))],
visibleOrigin = firstArray.filter(item => newOrigin.includes(item.value));

this.setState({ displayOrigin: visibleOrigin });

How to get the value inside the array culture.

Any advice, any help ? Thank you.


Solution

  • So. I found a solution to my issue. Here's the code :

    _nameFunction = () => {
        let filteredSecondArray = [...new Set(this.state.secondArray.map(o => o.culture[0].value))];
        this.setState({
            firstArray: this.state.firstArray.filter(item => filteredSecondArray.includes(item.value))
        })
    }