2

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?

Wouter van Dijke
  • 662
  • 1
  • 7
  • 17
  • 3
    I bet it doesn't look like that because that would give you an error. Add `:` between your key/values. Also you shouldn't expect that array order because object keys are unordered. – Andy Apr 10 '16 at 19:10
  • Possible duplicate of [JavaScript object: access variable property by name as string](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string) – Amit Apr 10 '16 at 19:12

2 Answers2

2

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>');
 
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Another way to do this using loadash

_.map(wordlist, function (a) {return a.count;})

Devank
  • 159
  • 2
  • 9