Jack The Baker
Jack The Baker

Reputation: 1903

ReactJS/JavaScript find array in object

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

Answers (3)

Pranav C Balan
Pranav C Balan

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

faruk
faruk

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

normalizr

Upvotes: 1

Nina Scholz
Nina Scholz

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

Related Questions