繁体   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