簡體   English   中英

javascript:當我知道 id 時從數組中獲取對象

[英]javascript: get object from array when I know id

這是我在 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',  
  }
]

我只需要獲取我知道其 id 的對象並將其分配給一個變量。 我知道我需要一個 ID 為 1 的對象,所以我想:

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

使用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在其原型上有一個filter函數,允許您使用函數過濾值,該函數依次傳遞數組中的每個值。 如果您在函數中指定的條件返回 true,則返回您的值。

所以在這種情況下:

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)

然后,如果您只知道會找到一個值,則只需獲取 foundValues 數組中的第一項:

const foundItem = foundValues[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM