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)

1
  • 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 ==. Commented Feb 9, 2020 at 21:01

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.