我需要在对象数组中找到一个对象,但是我需要找到的对象可以在其中一个对象的另一个数组中。
我使用递归方法尝试了forEach循环的许多变体
{
"id": 1,
"messages": [{
"id": 4,
"message": "XXXXXXXX",
"code": "XXXXXX",
"subMessages": null
}, {
"id": 8,
"message": "XXXXXXXX",
"code": "XXXXXX",
"subMessages": [{
"id": 9,
"message": "XXXXXXXX",
"code": "XXXXXX",
"subMessages": null
}
]
}, {
"id": 10,
"message": "XXXXXXXX",
"code": "XXXXXX",
"subMessages": [{
"id": 11,
"message": "XXXXXXXX",
"code": "XXXXXX",
"subMessages": [{
"id": 12,
"message": "XXXXXXXX",
"code": "XXXXXX",
"subMessages": null
}
]
}
]
}
]
}
嵌套计数未知,并且可以超过示例中所示的数量,并且每个数组可以包含1条以上的消息。我正在尝试通过ID查找消息(ID在所有消息中都是唯一的)。
有什么提示吗?
答案 0 :(得分:0)
From what you mentioned, it looks like you just need to get the message against an id.
If you need the entire message object, replace the line of code `returnData = messageObj.message;` with `returnData = messageObj;`
I have used array.some to achieve this instead of creating a for loop
var messagesData = {
"id": 1,
"messages": [{
"id": 4,
"message": "4XXXXXXXX",
"code": "XXXXXX",
"subMessages": null
}, {
"id": 8,
"message": "8XXXXXXXX",
"code": "XXXXXX",
"subMessages": [{
"id": 9,
"message": "9XXXXXXXX",
"code": "XXXXXX",
"subMessages": null
}]
}, {
"id": 10,
"message": "10XXXXXXXX",
"code": "XXXXXX",
"subMessages": [{
"id": 11,
"message": "11XXXXXXXX",
"code": "XXXXXX",
"subMessages": [{
"id": 12,
"message": "12XXXXXXXX",
"code": "XXXXXX",
"subMessages": null
}]
}]
}]
};
function getMessageById(id) {
var returnData;
function searchForMessage(messages) {
messages.some(function(messageObj) {
if (messageObj.id === id) {
returnData = messageObj.message;
return true;
} else if (messageObj.subMessages && messageObj.subMessages.length) {
return searchForMessage(messageObj.subMessages);
} else {
return false;
}
});
}
searchForMessage(messagesData.messages);
return returnData;
}
console.log(getMessageById(11));
console.log(getMessageById(4));
console.log(getMessageById(12));
Here is my jsfiddle link with the same code - https://jsfiddle.net/karthikeyan_shanmugavadivelan/3o0udv7f/11/