Javascript 如何在对象数组上的id数组中查找id?
我正在尝试使用Javascript 如何在对象数组上的id数组中查找id?,javascript,reactjs,Javascript,Reactjs,我正在尝试使用find()方法: // data: demands = [ { "name": "first demand", "process": "31839", "categoryID": [ { "_id": "1234", "name": "first", "co
find()
方法:
// data:
demands = [
{
"name": "first demand",
"process": "31839",
"categoryID": [
{
"_id": "1234",
"name": "first",
"color": "green"
},
{
"_id": "1235",
"name": "second",
"color": "red"
}
]
},
{
"name": "second demand",
"process": "90123",
"categoryID": [
{
"_id": "4321",
"name": "third",
"color": "black"
},
{
"_id": "1357",
"name": "fourth",
"color": "yellow"
}
]
}
]
但我总是未定义,那么如何在嵌套对象数组中获取id呢
我也尝试过使用map和find,或者在另一个find中使用find,但都不起作用。我是javascript的初学者,不知道该怎么做。您的JSON应该有双引号而不是单引号因为categoryID是一个数组,所以应该使用索引访问它。访问id的正确方法是在categoryID后面加一个索引,例如
元素.categoryID[0]。\u id
我解决了如下问题:
let flag = false;
const findcategory = demands.map(
(demand) => demand.categoryID.filter((category) => category._id === content._id),
);
findcategory.forEach((element) => {
if (element.length !== 0) {
flag = true;
}
});
if (!flag) {
// do this
} else {
// do that
}
我不认为这是最优化的方法,但它奏效了 你的
要求
是一个绝对无效的JSON看起来你的“categoryID”应该是一个objectscategoryID数组也是一个数组;您还需要迭代它。我错过了编写它,但我的json已经有双引号了。现在它已经编辑完毕;这不是以前。
let flag = false;
const findcategory = demands.map(
(demand) => demand.categoryID.filter((category) => category._id === content._id),
);
findcategory.forEach((element) => {
if (element.length !== 0) {
flag = true;
}
});
if (!flag) {
// do this
} else {
// do that
}