简体   繁体   中英

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',  
  },

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM