有数据时对象未定义

时间:2020-05-05 09:17:39

标签: reactjs

我有一个包含对象的数组,如下图所示

[
    {
    _id: "12",
    data: { _id: "123", isDelete: false, name: "afd" },
    createdAt: "2020-04-11T08:38:15.966Z",
    shop_id: "sfd",
    updatedAt: "2020-04-27T02:07:12.271Z"
    },
    {
    _id: "12",
    data: { _id: "123", isDelete: false, name: "ffd" },
    createdAt: "2020-04-11T08:38:15.966Z",
    shop_id: "sfd",
    updatedAt: "2020-04-27T02:07:12.271Z"
    },
]

这是我过滤时

brands.filter(brand => {
      console.log(brand);// like above data
      console.log(brand.data);// show brand.data
      console.log(brand.data._id);//error brand.data is not defined
})

我已经尝试了

brands.filter(brand => {
      let a = brand.data;
      console.log(a._id);// error a is null
})

我需要获取brand.data.name,就像循环时一样,它需要打印afdffd

2 个答案:

答案 0 :(得分:1)

根据您的问题,是否要做的就是记录brand.data.name的值,那么使用filter毫无意义。

您可以仅使用forEach

const brands = [
    {
    _id: "12",
    data: { _id: "123", isDelete: false, name: "afd" },
    createdAt: "2020-04-11T08:38:15.966Z",
    shop_id: "sfd",
    updatedAt: "2020-04-27T02:07:12.271Z"
    },
    {
    _id: "12",
    data: { _id: "123", isDelete: false, name: "ffd" },
    createdAt: "2020-04-11T08:38:15.966Z",
    shop_id: "sfd",
    updatedAt: "2020-04-27T02:07:12.271Z"
    }
];

brands.forEach(brand => { console.log(brand.data.name) });

如果您想将名称存储在数组中而不是仅记录它们,则可以使用map

const brands = [
    {
    _id: "12",
    data: { _id: "123", isDelete: false, name: "afd" },
    createdAt: "2020-04-11T08:38:15.966Z",
    shop_id: "sfd",
    updatedAt: "2020-04-27T02:07:12.271Z"
    },
    {
    _id: "12",
    data: { _id: "123", isDelete: false, name: "ffd" },
    createdAt: "2020-04-11T08:38:15.966Z",
    shop_id: "sfd",
    updatedAt: "2020-04-27T02:07:12.271Z"
    }
];

const brandNames = brands.map(brand => brand.data.name);
console.log(brandNames);

答案 1 :(得分:0)

JavaScript过滤器适用于数组。因此,考虑到您要过滤嵌套对象(基于id)(即数据),因此代码应如下所示-

const brands = [
    {
    _id: "12",
    data: { _id: "1", isDelete: false, name: "afd" },
    createdAt: "2020-04-11T08:38:15.966Z",
    shop_id: "sfd",
    updatedAt: "2020-04-27T02:07:12.271Z"
    },
    {
    _id: "13",
    data: { _id: "2", isDelete: false, name: "ffd" },
    createdAt: "2020-04-11T08:38:15.966Z",
    shop_id: "sfd",
    updatedAt: "2020-04-27T02:07:12.271Z"
    },
]

const updatedBrands = brands.map(brand => {(
  ...brand, brand.data.filter(key => key._id === '1') 
}))

您必须首先使用javascript映射方法来遍历数组,然后可以按ID过滤数据对象。希望这会有所帮助。