bonlim
bonlim

Reputation: 193

How can I filter 2 object arrays in React?

const obj1 = [{'food': ['apple'], 'drink': ['wine', 'juice']}];

const obj2 = [{id: 1, 'food': ['apple'], dummy: 'test', 'drink':['wine', 'juice']}, 
              {id: 2, 'food': 'banana', dummy: 'test', 'drink':['juice']},
              {id: 3, 'food': ['apple', 'banana'], dummy: 'test'},'drink':['juice']}
              ];


//and result should be like this
const result = [{id:1, 'food': ['apple'], 'drink': ['wine', 'juice']}];

if there's two object arrays, how can I filter obj1 on obj2? What I'm going to do is

  1. if obj1 has same value with obj2, leave obj2's objects that contains same value with obj1.

  2. set the state with those remained objects.

this is how I tried.
the problem of this logic is
returned value contains only filtered value.
ex) {food:['banana]}
but It has to return all object that contain 'banana', not only 'banana'.
(so that I can set State with filtered result)

//key arg is recived key from outside. (it should be 'food' or 'drink')

const showFilteredRes = (obj1, key) => {
    let filteredRes = {};

    obj2.forEach((obj2) => {
      for (let filters in obj1) {
        for (let infos in obj2) {
          if (filters === infos) {
            filteredRes[infos] = obj2[key];
            console.log(filteredRes);
          }
        }
      }
    });
  };


how can I develop this code?

I edited my example because my explanation was too poor.

Upvotes: 0

Views: 112

Answers (2)

Ram Sankhavaram
Ram Sankhavaram

Reputation: 1228

const obj1 = [{
  'food': ['banana'],
  'drink': ['wine', 'juice']
}];

const obj2 = [{
    id: 1,
    'food': ['apple', 'custard'],
    dummy: 'test',
    'drink': ['wine', 'juice']
  },
  {
    id: 2,
    'food': ['banana'],
    dummy: 'test',
    'drink': ['juice']
  },
  {
    id: 3,
    'food': ['apple', 'banana'],
    dummy: 'test',
    'drink': ['juice', 'wine']
  }
];


const showFilteredRes = (filtered, key) => {
  let result = [];
  filtered.forEach((filteredObj) => {
    obj2.forEach((obj) => {
      if (JSON.stringify(obj[key]) == JSON.stringify(filteredObj[key])) {
        result.push(obj);
      }
    })
  })
  console.log(result);
};

showFilteredRes(obj1, "food");

Looping though the first Object and acquire the desired object using the deep compare arrays with same key.

Upvotes: 1

Rohan Agarwal
Rohan Agarwal

Reputation: 2609

Make use of some() :

const showFilteredRes = (filtered, key) => {
    let filteredRes = {};
    obj2.forEach(entry => {
    if(entry[key].some(item => obj1[key].includes(item)))
    {
        console.log(filteredRes);
    }
 }

Upvotes: 0

Related Questions