shopwaredev21
shopwaredev21

Reputation: 15

javascript: get object from array when I know id

this is my array in js:

const array = [
  {
    id: 1,
    userId: 1,
    title: 'test1',  
  },
  {
    id: 2,
    userId: 1,
    title: 'test2',  
  },
  {
    id: 3,
    userId: 1,
    title: 'test3',  
  },
  {
    id: 4,
    userId: 1,
    title: 'test4',  
  }
]

and I only need to grab the object where I know its id and assign it to a variable. I know that I will need an object with id number 1 so I would like to:

const item = {
    id: 1,
    userId: 1,
    title: 'test1',  
  },

Upvotes: 0

Views: 274

Answers (2)

Will Jenkins
Will Jenkins

Reputation: 9907

Array has a filter function on its prototype that allows you to filter the values using a function, which gets passed each value in the array in turn. If the condition you specify in your function returns true, your value is returned.

So in this case:

const myArray = [
  {
    id: 1,
    userId: 1,
    title: 'test1',  
  },
  {
    id: 2,
    userId: 1,
    title: 'test2',  
  },
  {
    id: 3,
    userId: 1,
    title: 'test3',  
  },
  {
    id: 4,
    userId: 1,
    title: 'test4',  
  }
]

const idToFind = 1;

const foundValues = myArray.filter(item => item.id === idToFind)

Then if you knew only one value would you found, you would just take the first item in the foundValues array:

const foundItem = foundValues[0]

Upvotes: 1

Taki
Taki

Reputation: 17664

Use Array.find :

const array = [
  {
    id: 1,
    userId: 1,
    title: "test1"
  },
  {
    id: 2,
    userId: 1,
    title: "test2"
  },
  {
    id: 3,
    userId: 1,
    title: "test3"
  },
  {
    id: 4,
    userId: 1,
    title: "test4"
  }
];

const item = array.find(({ id }) => id === 1);

console.log(item);

Upvotes: 3

Related Questions