我跟随JSON,我的车主是他们的车主。在lodash中是否有更好的方法可以从预定义列表中获取汽车数量。
例如,
{
"data": [
{"ownerId":"00001", "make": "Honda"},
{"ownerId":"00002", "make": "Nissan"},
{"ownerId":"00003", "make": "Audi"},
{"ownerId":"00004", "make": "Porsche"},
{"ownerId":"00005", "make": "Honda"},
{"ownerId":"00006", "make": "Honda"},
{"ownerId":"00007", "make": "Audi"},
{"ownerId":"00008", "make": "Volkswagen"},
{"ownerId":"00009", "make": "Honda"},
{"ownerId":"00010", "make": "Porsche"},
{"ownerId":"00011", "make": "Volkswagen"}
]
}
计算计数的过滤器列表:
["Honda", "Audi", "Porsche"]
预期结果:
[{"Audi": 2}, {"Honda": 4}, {"Porsche": 2}]
输入JSON中还有其他汽车品牌,但由于过滤器列表没有,因此不予考虑。
答案 0 :(得分:1)
您可以使用_.countBy()
来获取和制作每个制作的计数,然后使用_.pick()
您想要的项目:
const cars = {"data":[{"ownerId":"00001","make":"Honda"},{"ownerId":"00002","make":"Nissan"},{"ownerId":"00003","make":"Audi"},{"ownerId":"00004","make":"Porsche"},{"ownerId":"00005","make":"Honda"},{"ownerId":"00006","make":"Honda"},{"ownerId":"00007","make":"Audi"},{"ownerId":"00008","make":"Volkswagen"},{"ownerId":"00009","make":"Honda"},{"ownerId":"00010","make":"Porsche"},{"ownerId":"00011","make":"Volkswagen"}]};
const list = ["Honda", "Audi", "Porsche"];
const result = _.pick(_.countBy(cars.data, 'make'), ["Honda", "Audi", "Porsche"]);
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
&#13;