在对象数组中查找特定对象
Find a specific object in an array of objects
我不明白,因为我使用方法“查找”,但我得到“未定义”...
我的数据:
[
{ "id": 2, "title": "My project", "nameStructure": "Entreprise", "studies":
[
{"id": 3, "name": "My stidue", "status": "in prepa" },
{ "id": 4, "name": "My second study ", "status": "In"}
],
"typeStructure": "Entreprise"
},
{ "id": 3, "title": "My project 2", "nameStructure": "Entreprise 2", "studies":
[
{"id": 4, "name": "My stidue 2", "status": "in prepa" },
{ "id": 5, "name": "My second study 2 ", "status": "In"}
],
"typeStructure": "Entreprise 2"
},
...
]
例如,我只想拥有 ID 为 2 的对象。
所以我写道:
const id = 2
myarray.filter(p => p.id === id);
但它不起作用...我总是得到“未定义”
感谢帮助
ID 是一个数字,因此您需要删除 2
周围的引号
myarray.filter(p => p.id === 2);
和 Javascript 中的运算符 === 表示 2 应该等于“2”,如值和类型
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality
const arr = [
{
id: 2,
title: "My project",
nameStructure: "Entreprise",
studies: [
{ id: 3, name: "My stidue", status: "in prepa" },
{ id: 4, name: "My second study ", status: "In" }
],
typeStructure: "Entreprise"
},
{
id: 3,
title: "My project 2",
nameStructure: "Entreprise 2",
studies: [
{ id: 4, name: "My stidue 2", status: "in prepa" },
{ id: 5, name: "My second study 2 ", status: "In" }
],
typeStructure: "Entreprise 2"
}
];
const newItem = arr.find((item) => item.id === 2);
console.log("newItem>>>>", newItem);
我不明白,因为我使用方法“查找”,但我得到“未定义”... 我的数据:
[
{ "id": 2, "title": "My project", "nameStructure": "Entreprise", "studies":
[
{"id": 3, "name": "My stidue", "status": "in prepa" },
{ "id": 4, "name": "My second study ", "status": "In"}
],
"typeStructure": "Entreprise"
},
{ "id": 3, "title": "My project 2", "nameStructure": "Entreprise 2", "studies":
[
{"id": 4, "name": "My stidue 2", "status": "in prepa" },
{ "id": 5, "name": "My second study 2 ", "status": "In"}
],
"typeStructure": "Entreprise 2"
},
...
]
例如,我只想拥有 ID 为 2 的对象。
所以我写道:
const id = 2
myarray.filter(p => p.id === id);
但它不起作用...我总是得到“未定义”
感谢帮助
ID 是一个数字,因此您需要删除 2
周围的引号myarray.filter(p => p.id === 2);
和 Javascript 中的运算符 === 表示 2 应该等于“2”,如值和类型
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality
const arr = [
{
id: 2,
title: "My project",
nameStructure: "Entreprise",
studies: [
{ id: 3, name: "My stidue", status: "in prepa" },
{ id: 4, name: "My second study ", status: "In" }
],
typeStructure: "Entreprise"
},
{
id: 3,
title: "My project 2",
nameStructure: "Entreprise 2",
studies: [
{ id: 4, name: "My stidue 2", status: "in prepa" },
{ id: 5, name: "My second study 2 ", status: "In" }
],
typeStructure: "Entreprise 2"
}
];
const newItem = arr.find((item) => item.id === 2);
console.log("newItem>>>>", newItem);