I have an object like this:
var shoppers = {
"Bob": {favoriteApple: "Honeycrisp"},
"Sue": {favoriteApple: "Braeburn"},
"Derek": {favoriteApple: "Honeycrisp"}
}
I want to iterate through this object and count how many people prefer each kind of apple. How can I do this?
On a related note, why does this log as undefined
three times instead of logging the actual apple name?
for (var person in shoppers) {
console.log(person.favoriteApple); // undefined
}
You can use following
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>
Regarding the second question
why does
console.log(person.favoriteApple);
log as undefined three times instead of logging the actual apple name?
for (var person in shoppers) {
console.log(person.favoriteApple);
}
person
in the for
is the key of the object shoppers
. To access the actual value of the key use shoppers[person]
.
Code:
for (var key in shoppers) {
// To stop showing the inherited/prototyped properties
if (shoppers.hasOwnProperty(key)) {
console.log(shoppers[key].favoriteApple);
}
}
When you use
for (var prop in obj)
It iterates over keys of this object. So, in your case person
will be Bob
, Sue
, Derek
.
All you need is to use this key to access a value of a property:
for (var person in shoppers)
{
console.log(shoppers[person]);
}
you can keep a tally like so:
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}
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.