javascript - Function to turn an array of objects into an array of primitives, by key -
i need js function able turn :
[ { prop1: 'val1', prop2: 'val2' }, { prop1: 'val3', prop2: 'val4' }, { prop1: 'val5', prop2: 'val6' } ] into :
['val1', 'val3', 'val5'] // took each object's .prop1 as may have noticed question's title, i'm not sure of right way word (english not native language).
as consequence, kinda hard find googling, wrote own ; have feeling there's native js function job. there ?
(for record, here's wrote :)
function dosomethingbykey(objarr, key) { var result = []; (i in objarr) { if (objarr[i].hasownproperty(key)) { result.push(objarr[i][key]); } } return result; }
iterating on array of objects , getting 1 key of each object typically called "plucking", though there other names. in modern javascript versions can trivially implemented map:
var arr = [{ foo : 'bar', baz : 42 }, { foo : ... }, ...], foos = arr.map(function (obj) { return obj.foo; }); if want abstract function:
function pluck(arr, key) { return arr.map(function (obj) { return obj[key]; }); } pluck(arr, 'foo'); if hasownproperty concern, function optimal gets already.
Comments
Post a Comment