使用 lodash 迭代对象的更好方法
使用 lodash 我想知道是否有更好的方法来做到这一点。
我有一个如下所示的数组对象。
{
"ALFA ROMEO": {
"MITO": [{
"carData": "stuff"
}]
},
"AUDI": {
"A1": [{
"carData": "stuff"
},
{
"carData": "stuff"
}
],
"Q3": [{
"carData": "stuff"
}],
"A3": [{
"carData": "stuff"
},
{
"carData": "stuff"
},
{
"carData": "stuff"
}
]
}
}
我正在使用 _.forEach 来迭代对象以构造与此类似的输出:
ALFA ROMEO - 1
MITO (1)
AUDI - 5
A1 (2)
Q3 (1)
A3 (2)
使用这个我可以到达那里:
_.forEach(jData, (val, key) => {
console.log(key)
_.forEach(val, (val, key) => {
console.log(' ' + key + ' (' + val.length + ')')
})
})
这给了我这个:
ALFA ROMEO
MITO (1)
AUDI
A1 (2)
Q3 (1)
A3 (2)
我的问题是这样的:
a)是否有更好的方法来做到这一点而不需要双循环?
b) 是通过合计模型计数来获得每个品牌总数的唯一方法,还是有更好的方法?
谢谢。
Using lodash I'm wondering if there is a better way of doing this.
I've got an array object like below.
{
"ALFA ROMEO": {
"MITO": [{
"carData": "stuff"
}]
},
"AUDI": {
"A1": [{
"carData": "stuff"
},
{
"carData": "stuff"
}
],
"Q3": [{
"carData": "stuff"
}],
"A3": [{
"carData": "stuff"
},
{
"carData": "stuff"
},
{
"carData": "stuff"
}
]
}
}
I'm using _.forEach to iterate through the object to structure the output simular to this:
ALFA ROMEO - 1
MITO (1)
AUDI - 5
A1 (2)
Q3 (1)
A3 (2)
Using this I can get part way there:
_.forEach(jData, (val, key) => {
console.log(key)
_.forEach(val, (val, key) => {
console.log(' ' + key + ' (' + val.length + ')')
})
})
Which give me this:
ALFA ROMEO
MITO (1)
AUDI
A1 (2)
Q3 (1)
A3 (2)
My question is this:
a) Is there a better way of doing this without a double loop?
b) Is the only way to get a total for each make by totalling up the model counts, or is there a better way of doing this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有嵌套循环就无法做到这一点,因为您需要打印每个模型。
您可以使用 _.sumBy() 来获取模型的总长度,以便您可以在循环之前显示它。
There's no way to do it without nested looping, since you need to print each model.
You can use
_.sumBy()
to get the total lengths of the models, so you can show that before the loop.