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 , returnstrue
if item should kept orfalse
if should not kept. returns new filtered array.every
takes callback examines item of array , returns eithertrue
orfalse
. if each item in array causes function returntrue
,every
call returnstrue
, singlefalse
value causes returnfalse
.the
object.keys(object).every
testing if every key ofobject
has value matches corresponding property value in item ofarray
. if so, include item in filtered version of array.
Comments
Post a Comment