2

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)
Jack The Baker
  • 1,781
  • 1
  • 20
  • 51
  • 3
    `===` compares both the type and the value, and you're comparing a `string` and a `number` which means `o.id === v` will never be `true`, try using just `==`. – Titus Feb 09 '20 at 21:01

3 Answers3

3

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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?

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

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

normalizr

faruk
  • 141
  • 6