0

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
})

4
  • 1
    arr.every(e => *condition*) will return true if every element of array matches the condition. Commented Apr 28, 2021 at 0:17
  • Can you please include your desired result in your question? Commented Apr 28, 2021 at 0:37
  • if(collection[i].hasOwnProperty(newArr[s]) === true) here i wanted to check if all the elements on the array matches the object properies and return that object, instead the if statement returns every object that matches 1 array element or more Commented Apr 28, 2021 at 0:40
  • which causes { "cookie": 2 } to log on output you can see that source has 2 properties { 'apple': 1, "cookie": 2 } Commented Apr 28, 2021 at 0:42

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

4 Comments

it still returns { "cookie": 2 } even tho source has 2 properties
answer edited...simple, just do the test the other way round again...
I don't understand how this result matches the requirements.
Basically Plvtinum wanted to filter out the objects with exactly the same keys, regardless of the values of the objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.