Reputation: 505
I am trying to work out how I can return a list with values from the own
key in the array bellow if the object name
value matches values in the lookupvalues array
lookupvalues = ["ross","linda"]
resources = [{own: "car", name: "bob"},{own: "bike", name: "ross"},{own: "plane", name: "linda"}]
wanted_output = ["bike","plane"]
I am struggling a bit with a good method to use for when I need to compare value in an object with array values. Is there a reasonable straight forward way to do this?
I must say how impressed I am that I got 4 replies with working examples at the same time!
Upvotes: 0
Views: 362
Reputation: 329
resources.filter(item => lookupvalues.indexOf(item.name) > -1).map(item => item.own)
Upvotes: 1
Reputation: 16908
You can take the help of Array#filter
and Array#map
:
const lookupvalues = ["ross","linda"]
const resources = [{own: "car", name: "bob"},{own: "bike", name: "ross"},{own: "plane", name: "linda"}]
const filterRes = (arr) => {
const lookup = new Set(lookupvalues);
return arr.filter(({name}) => lookup.has(name))
.map(({own}) => own);
}
console.log(filterRes(resources));
Upvotes: 1
Reputation: 1055
resources.filter(resource => lookupvalues.includes(resource.name))
.map(resource => resource.own);
This will filter by the items that have names that are included in lookupvalues
, and then transform the array into an array of the own
values of those remaining.
Upvotes: 1
Reputation: 14871
One way (array method chaining) is that you could filter
by name
and map
to grap each's own
const lookupvalues = ["ross", "linda"]
const resources = [
{ own: "car", name: "bob" },
{ own: "bike", name: "ross" },
{ own: "plane", name: "linda" },
]
const res = resources
.filter(({ name }) => lookupvalues.includes(name))
.map(({ own }) => own)
console.log(res)
Upvotes: 1