在对象数组中查找特定对象

时间:2021-04-01 10:29:36

标签: javascript nuxtjs

我不明白,因为我使用“查找”方法,但得到“未定义”... 我的数据:

[ 
{ "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);

但它不起作用......我总是得到“未定义”

感谢帮助

2 个答案:

答案 0 :(得分:2)

ID 是一个数字,因此你需要去掉 2 周围的引号

myarray.filter(p => p.id === 2);

和 Javascript 中的运算符 === 意味着 2 应该等于“2”,如值和类型

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality

答案 1 :(得分:1)

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