hello world
hello world

Reputation: 1755

looping thru array of objects

hey guys so I'm trying to solve this problem here

Make a function that looks through a list (first argument) and returns an array of all objects that have equivalent property values (second argument).

but i can't seem to loop thru an array of objects if my life depended on it..... Here is my following code

function where(collection, source) {
  for(var prop in collection){
    if(collection.hasOwnProperty(prop)){
      console.log("collection." + prop + "=" + collection[prop]);
    }
  }
}

where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' });

i was reading documents on hasOwnProperty method and for in loops but it seems like I am utilizing them wrong, any guidance is appreciated, thanks.

THIS IS NOT A DUPLICATE

Upvotes: 0

Views: 147

Answers (2)

sfletche
sfletche

Reputation: 49704

The for...in loop is not what you want for iterating over arrays in javascript.

Use the sequential for loop to loop through the array, and the for..in loop to iterate over the keys of the object...

for(var i=0; i<collections.length; i+=1) {
  for(var prop in collections[i]){
    if(collections[i].hasOwnProperty(prop)){
      console.log("collection." + prop + "=" + collections[i][prop]);
    }
  }
}

Upvotes: 1

Wand Maker
Wand Maker

Reputation: 18762

One can use filter method to filter out elements that satisfy the condition. Also, since comparison of objects is needed in evaluating the condition, and there does not seem to be an equals method in JavaScript for Objects, one has to do additional work to check equality.

Here is one way the problem mentioned in question can be solved

function where(collection, source) {
  return collection.filter(function(item) { 
     return Object.keys(source).every(function(k){ return item[k] == source[k] });
  });
}

console.log (where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet'}));

Output

[ { first: 'Tybalt', last: 'Capulet' } ]

Upvotes: 1

Related Questions