我有一个JSON文件。我想找到一个键值对相似的JSON对象的长度。喜欢,
https://api.myjson.com/bins/h5mgv
[
{
"receive_date": "2013-11-04",
"responses": "2",
"name": "west"
},
{
"receive_date": "2013-11-04",
"responses": "8668",
"name": "west"
},
{
"receive_date": "2013-11-13",
"responses": "121",
"name": "east"
}
]
在上面的示例中,长度为2,"name": "west"
,长度为1 "name": "east"
。我想迭代JSON并使用Javascript为键name
找到相同的值。输出应该看起来像,
east : 1
west : 2
通过使用length()
,我可以找到整个JSON的长度,但建议的方法是查找相同键值的长度。
答案 0 :(得分:1)
您可以使用reduce来获取列出每个名称计数的新对象:
const myArray = [
{
"receive_date": "2013-11-04",
"responses": "2",
"name": "west"
},
{
"receive_date": "2013-11-04",
"responses": "8668",
"name": "west"
},
{
"receive_date": "2013-11-13",
"responses": "121",
"name": "east"
}
]
const myCounts = myArray.reduce((counts, item) => {
if (counts[item.name] === undefined) counts[item.name] = 0;
counts[item.name]++;
return counts;
}, {});
console.log(myCounts);
这会产生结果:
{
"west": 2,
"east": 1
}