我有一个这样的对象:
var shoppers = {
"Bob": {favoriteApple: "Honeycrisp"},
"Sue": {favoriteApple: "Braeburn"},
"Derek": {favoriteApple: "Honeycrisp"}
}
我想迭代这个对象并计算有多少人喜欢每种苹果。我怎么能这样做?
在相关的说明中,为什么这会记录为undefined
三次,而不是记录实际的苹果名称?
for (var person in shoppers) {
console.log(person.favoriteApple); // undefined
}
答案 0 :(得分:2)
您可以使用以下
var shoppers = {
"Bob": {
favoriteApple: "Honeycrisp"
},
"Sue": {
favoriteApple: "Braeburn"
},
"Derek": {
favoriteApple: "Honeycrisp"
}
};
// Create empty object to store item count
var countObj = {};
// Get the array of keys in object using `Object.keys`
// Iterate over keys array using `forEach`
Object.keys(shoppers).forEach(function(key) {
// Get the value of favoriteApple
var favApple = shoppers[key].favoriteApple;
// If count exists, increment it else add count as 1
countObj[favApple] = countObj[favApple] ? countObj[favApple] + 1 : 1;
});
console.log(countObj);
document.getElementById('result').innerHTML = JSON.stringify(countObj, 0, 4);
<pre id="result"></pre>
关于第二个问题
为什么
console.log(person.favoriteApple);
记录为未定义三次而不是记录实际的苹果名称?
for (var person in shoppers) {
console.log(person.favoriteApple);
}
person
中的 for
是对象shoppers
的关键字。要访问密钥的实际值,请使用shoppers[person]
。
<强>代码:强>
for (var key in shoppers) {
// To stop showing the inherited/prototyped properties
if (shoppers.hasOwnProperty(key)) {
console.log(shoppers[key].favoriteApple);
}
}
答案 1 :(得分:1)
使用时
for (var prop in obj)
迭代此对象的键。因此,在您的情况下,person
将为Bob
,Sue
,Derek
。
您只需使用此键访问属性值:
for (var person in shoppers)
{
console.log(shoppers[person]);
}
答案 2 :(得分:1)
你可以保持这样的记录:
var favoriteApples = {};
for(var name in shoppers) {
var person = shoppers[name];
if(!favoriteApples[person.favoriteApple]) {
favoriteApples[person.favoriteApple] = 1;
}else{
favoriteApples[person.favoriteApple]++;
}
}
console.log(favoriteApples);
// prints Object {Honeycrisp: 2, Braeburn: 1}
答案 3 :(得分:0)
var shoppers = {
"Bob": {favoriteApple: "Honeycrisp"},
"Sue": {favoriteApple: "Braeburn"},
"Derek": {favoriteApple: "Honeycrisp"}
}
$.each(shoppers,function(key,val){
console.log(key);
$.each(val,function(k,v){
console.log(k + " " + v)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>