我下面的 Json 对象包含与其制造商关联的汽车。我想从 Json 对象中获取汽车总数以及对象中特定汽车的出现次数。
var Cars = { "manufacturer":"Car":
[{"Saab":"Automobile AB"},
{"Volvo":"V40"},
{"BMW":"Estoril Blue"},
{"Volvo":"V40"},
]};
我尝试使用过滤器
,但由于过滤器仅特定于数组
,因此无法将其与 Json 对象一起使用。下面是源代码。
var Cars = {"manufacturer":"Car":
[{"Saab":"Automobile AB"},
{"Volvo":"V40"},
{"BMW":"Estoril Blue"},
{"Volvo":"V40"},
]};
var volvo = "V40";
var numberOfCars = Cars.filter(function (x) {
return x === volvo;
}).length;
我期望上述源代码的输出为2。但是我得到了一个异常
Cars.filter is not a function
我需要你们帮我获取V40
的出现次数(即2),以及汽车的总数(即4)。
最佳答案
遍历对象的属性非常容易。一种方法是使用 Object.entries 获取属性和值的数组;
var Cars = [{"Saab":"Automobile AB"}, {"Volvo":"V40"}, {"BMW":"Estorill Blue"}, {"Volvo":"V40"}];
let properties = Object.entries(Cars);
console.log("Number of cars: ", Cars.length);
console.log("Number of Volvos: ", Cars.filter((car) => Object.keys(car)[0] === "Volvo").length);
关于javascript - 如何使用javascript获取Json对象中字符串的实例数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56689535/