首页 > 解决方案 > javascript:当我知道 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',  
  },

标签: javascript

解决方案


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


推荐阅读