Reputation: 692
In a script I've got an object containing several other objects, that all have the same structure. It looks like this:
wordlist = {word1: {count:2},
word2: {count:5},
word3: {count:3},
word4: {count:2}}
I want to generate an array of just the counts of each word, so it would look like [2, 5, 3, 2].
Is there any way to do this in Node.js?
I would imagine using a for-loop where each iteration goes to the next sub-object, but how would I select the sub-object by its position in the main object? In an array you can type arrayName[2] to get the third entry in that array, is a similar thing possible with an object?
Upvotes: 2
Views: 90
Reputation: 159
Another way to do this using loadash
_.map(wordlist, function (a) {return a.count;})
Upvotes: 0
Reputation: 386680
You could iterate over the keys of a proper object and map the values of count
.
var wordlist = { word1: { count: 2 }, word2: { count: 5 }, word3: { count: 3 }, word4: { count: 2 } },
result = Object.keys(wordlist).map(function (k) {
return wordlist[k].count;
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
ES6 Version
var wordlist = { word1: { count: 2 }, word2: { count: 5 }, word3: { count: 3 }, word4: { count: 2 } },
result = Object.keys(wordlist).map(k => wordlist[k].count);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Upvotes: 2