Parth Tiwari
Parth Tiwari

Reputation: 486

How to filter object?

How to filter the object value from desc based on the main.

Is there any possible way i can get value qwer and save into variable. As main contain 3 so i want to fetch the desc object value qwer in Reactjs

const data = {
  main: "3",
  desc: [
    {
      id: "1",
      value: "xyz"
    },
    {
      id: "2",
      value: "abc"
    },
    {
      id: "3",
      value: "qwer"
    },
    {
      id: "4",
      value: "cwer"
    }
  ]
};

Upvotes: 0

Views: 54

Answers (1)

hgb123
hgb123

Reputation: 14891

If the id in desc array is unique, you could use find (doc for Array.prototype.find())

const data = {
  main: '3',
  desc: [
    {
      id: '1',
      value: 'xyz'
    },
    {
      id: '2',
      value: 'abc'
    },
    {
      id: '3',
      value: 'qwer'
    },
    {
      id: '4',
      value: 'cwer'
    }
  ]
}

const res = data.desc.find(d => d.id === data.main)

console.log(res.value)

Upvotes: 2

Related Questions