Plvtinum
Plvtinum

Reputation: 317

How can I tell Javascript to filter array of objects

Im trying to figure out how can I tell javascript to filter array of objects, here's the code

I hope that I explained everything in code the //* is where the problem is.

function whatIsInAName(collection, source) { // first arg is the array of objects, second arg is the object i want to get matched
  let arr = [];
  let newArr = Object.getOwnPropertyNames(source); // this converts the object into an array

  for (let i = 0; i < collection.length; i++) { // loop through objects
    for (let s = 0; s < newArr.length; s++) { // loop through array
      if (collection[i].hasOwnProperty(newArr[s]) === true) { //* it returns an object if it matches 1 element of array
        console.log(collection[i]) // i want it to return only if all elements on the array matches
        arr.push(collection[i]);
      }
    }
  }
  return arr;
}

whatIsInAName([{
  "apple": 1,
  "cookie": 6
}, {
  "apple": 1,
  "bat": 2
}, {
  "cookie": 2
}, {
  "apple": 1,
  "cookie": 4
}, {
  "apple": 1,
  "bat": 2,
  "cookie": 2
}], {
  'apple': 1,
  "cookie": 2
})

Upvotes: 0

Views: 127

Answers (1)

Chong Lip Phang
Chong Lip Phang

Reputation: 9279

Try something like this:

let collection = [{ "apple": 1, "cookie": 6}, {"apple": 1, "bat": 2 }, { "cookie": 2 }, { "apple": 1, "cookie": 4 }, { "apple": 1, "bat": 2, "cookie": 2 }];
let source = { 'apple': 1, "cookie": 2 };

let filtered = collection.filter(e=>(
    Object.getOwnPropertyNames(e).every(ee=>source.hasOwnProperty(ee))&&
    Object.getOwnPropertyNames(source).every(ee=>e.hasOwnProperty(ee))));
console.log(filtered);

Upvotes: 1

Related Questions