我有以下代码来迭代来自对象的贴纸信息。为此,我使用两个嵌套。在lodash中有没有更好的方法来重构代码而不使用嵌套的forEach或任何更好的建议。
var stickers = [];
_.forEach(data.families.categories, function (category) {
_.forEach(category.stickers, function (sticker) {
stickers.push(sticker);
});
});
以下是对象样本
var data = {
"families": {
"id": "my_family",
"categories": [
{
"label": "sample-1",
"id": "family-0",
"stickers": [
"aa",
"bb",
"cc"
]
},
{
"label": "US",
"id": "family-1",
"stickers": [
"DD",
"EE"
]
},
{
"label": "sample-2",
"id": "family-2",
"stickers": [
]
},
{
"label": "sample-3",
"id": "family-3",
"stickers": [
"FF",
"GG",
"HH",
"II",
"JJ"
]
}
]
}
}
答案 0 :(得分:2)
Lodash提供了flatMap功能,可以做你想做的事情:
var stickers =_.flatMap(data.families.categories, 'stickers');
var data = {
"families": {
"id": "my_family",
"categories": [
{
"label": "sample-1",
"id": "family-0",
"stickers": [
"aa",
"bb",
"cc"
]
},
{
"label": "US",
"id": "family-1",
"stickers": [
"DD",
"EE"
]
},
{
"label": "sample-2",
"id": "family-2",
"stickers": [
]
},
{
"label": "sample-3",
"id": "family-3",
"stickers": [
"FF",
"GG",
"HH",
"II",
"JJ"
]
}
]
}
}
var stickers =_.flatMap( data.families.categories, 'stickers');
document.getElementById('result').textContent = JSON.stringify(stickers);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
<p>
<pre id="result"></pre>
</p>
答案 1 :(得分:1)
您可以将Array#reduce
与Array#concat
结合使用。
var data = { "families": { "id": "my_family", "categories": [{ "label": "sample-1", "id": "family-0", "stickers": ["aa", "bb", "cc"] }, { "label": "US", "id": "family-1", "stickers": ["DD", "EE"] }, { "label": "sample-2", "id": "family-2", "stickers": [] }, { "label": "sample-3", "id": "family-3", "stickers": ["FF", "GG", "HH", "II", "JJ"] }] } },
stickers = data.families.categories.reduce(function (r, category) {
return r.concat(category.stickers);
}, []);
console.log(stickers);
&#13;