javascript - Write a function that takes an array of objects and an object with properties & values -


write function takes array of objects , object properties , values. function return array of objects prop/vals match.

i know following, having lot of trouble understanding question itself. appreciated!

an example return :

thinglist = [ {age: 'four', type: 'cat', name: 'mammal'}, {age: 'six', type: 'dog', name: 'mammal'}, {age: 'seven', type: 'dog', name: 'mammal'}, {age: 'two', type: 'lizard', name: 'reptile'} ]   withvals( thinglist , {type: 'dog', name: 'mammal'} ) => [ {age: 'seven', type: 'dog', name: 'mammal'}, {age: 'six', type: 'dog', name: 'mammal'} ] 

i know how iterate on array , pull out values, have no idea how pass in object function well. iterate on see if values match.

this how see starting:

function withpropvalues(arr, obj) {     var newarray = [];     (var = 0; < arr.length; i++) {         if (arr[i] === obj) {             newarray.push(arr[i])         }     }     return newarray; } 

you need loop on properties of object , see if match same-named properties of each item in array. can property names object.keys(object), , there it's matter of accessing values bracket notation, e.g., object[key] === array[i][key].

generally, you're trying accomplished neatly filter, , match properties every on object.keys:

function withvals(array, object) {     var keys = object.keys(object);     return array.filter(function(item) {         return keys.every(function(k) { return item[k] === object[k]; });     }); } 
  • filter takes callback examines item array , returns true if item should kept or false if should not kept. returns new filtered array.

  • every takes callback examines item of array , returns either true or false. if each item in array causes function return true, every call returns true, single false value causes return false.

  • the object.keys(object).every testing if every key of object has value matches corresponding property value in item of array. if so, include item in filtered version of array.


Comments