Reputation: 1903
I have a string value
and an object obj
, want to convert value
to array
then find it in obj
by value, and get name
but it return undefined
, what I have missed?
let value = '3,4';
let obj = {
"DistrictData": [{
"id": 3,
"name": 'blah'
}, {
"id": 4,
"name": 'oops'
}]
}
let res = value.split(',').map((v, i) => obj.DistrictData.find(o => o.id === v))
console.log(res)
Upvotes: 2
Views: 89
Reputation: 115282
The split array contains string value and within find you are comparing string with number so either convert string to number or use ==
to ignore checking type. And finally get the name
property from the object.
let value = '3,4';
let obj = {
"DistrictData": [{
"id": 3,
"name": 'blah'
}, {
"id": 4,
"name": 'oops'
}]
}
let res = value.split(',').map((v, i) => (bj.DistrictData.find(o => o.id == v).name)
console.log(res)
Refer : Which equals operator (== vs ===) should be used in JavaScript comparisons?
Upvotes: 1
Reputation: 151
you can normalize array
to like
let obj = { "DistrictData": {"3":{ "id": 3,"name": 'blah'}, "4":{"id": 4,"name": 'oops'}}
then you can filter on name
Upvotes: 1
Reputation: 386883
You need to find with a number value, because split returns an array of strings. Then map the name as well.
let value = '3,4',
obj = { DistrictData: [{ id: 3, name: 'blah' }, { id: 4, name: 'oops' }] },
res = value
.split(',')
.map((v, i) => obj.DistrictData.find(o => o.id === +v))
.map(o => o.name);
console.log(res);
Upvotes: 3