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]; }); }); } filtertakes callback examines item array , returnstrueif item should kept orfalseif should not kept. returns new filtered array.everytakes callback examines item of array , returns eithertrueorfalse. if each item in array causes function returntrue,everycall returnstrue, singlefalsevalue causes returnfalse.the
object.keys(object).everytesting if every key ofobjecthas value matches corresponding property value in item ofarray. if so, include item in filtered version of array.
Comments
Post a Comment