mjo*_*ton 5 javascript arrays json object lodash
我有一个具有以下结构的 JSON API 响应
[
{
title: "top1",
sections: [
{
section_title: "section1",
content: [
{
content_title: "title1",
content_id: "id1"
},
{
content_title: "title2",
content_id: "id2"
}
]
},
{
section_title: "section2",
content: [
{
content_title: "title3",
content_id: "id3"
},
{
content_title: "title4",
content_id: "id4"
}
]
}
]
}, {
title: "top2",
sections: [...]
},
...
]
Run Code Online (Sandbox Code Playgroud)
我还有一小部分内容 ID arr2 = ['id2','id3']。我需要从 API 请求中搜索数据以查找包含在arr2.
我有一些可用的 lodash 代码,但我的嵌套 forEach 方法似乎不是最有效的方法:
_.forEach(response, function(top) {
_.forEach(top.sections, function(section) {
_.forEach(section.content, function(content) {
_.forEach(arr2, function(id) {
if(id === content.content_id) {
// Do stuff
}
})
})
})
})
Run Code Online (Sandbox Code Playgroud)
我该如何改进此代码?
经过一番思考,我实际上无法为您提供使用其他 lodash 函数的更优雅的解决方案。似乎为每种情况设置拥有的属性是forEach可行的方法。我可以做的唯一优化是通过使用普通的 javascriptforEach数组函数来避免使用 lodash,并使用它find来替换最里面的 forEach (可能会稍微提高性能)。
response.forEach((topItem) => {
topItem.sections.forEach((section) => {
section.content.forEach((content) => {
if(arr2.find((item) => { return item === content.content_id; })){
topItem.owned = true; section.owned = true; content.owned = true;
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
我对箭头函数语法也有个人偏好......