javascript - 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',
},
解决方案
使用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);
推荐阅读
- django - 在 Django 表单中保存并继续
- flutter - DropdownButton 始终处于禁用状态
- javascript - 对象可能在 Typescript 中的字符串值“未定义”
- c++ - 引用类不能从 C++ 中的 IAudioSessionNotification 继承
- php - 扩展服务器时使用不同的时区是否会产生不利影响?
- python - 在 selenium 中使用用户数据会导致删除扩展
- arrays - 根据Excel中的条件比较数组中的两个日期
- php - 在 Symfony 4 中配置 Monolog 通过 TCP 发送 GELF
- angular - 难以将数据显示为不同的列引导程序
- node.js - 在nodejs中查找2个文件之间的差异