4

a very beginner question below I'm sure, apologies for asking but I've had a good hunt on the matter with no luck... I'm looking to 'break' or 'expand' the following:

var words = { hello: 2, there: 3, heres: 1, text: 1 }

Into this:

var words = [{
  word: 'hello',
  count: 2
}, {
  word: 'there',
  count: 3
}, {
  word: 'heres',
  count: 1
}, {
  word: 'text',
  count: 1
}]

I've been messing around a lot with Underscore.js, but must be missing something very obvious. Any help will be greatly appreciated, thanks!

Matt
  • 53
  • 1
  • 1
  • 5

4 Answers4

11

You can do this with Object.keys() and map().

var words = { hello: 2, there: 3, heres: 1, text: 1 }
var result = Object.keys(words).map(e => ({word: e, count: words[e]}))
console.log(result)

You can also first create array and then use for...in loop to push objects.

var words = { hello: 2, there: 3, heres: 1, text: 1 }, result = [];
for(var i in words) result.push({word: i, count: words[i]})
console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
3

Possible solution using Array#map.

const words = { hello: 2, there: 3, heres: 1, text: 1 },
      res = Object.keys(words).map(v => ({ word: v, count: words[v] }));
      
      console.log(res);

Or Array#reduce.

const words = { hello: 2, there: 3, heres: 1, text: 1 },
      res = Object.keys(words).reduce((s,a) => (s.push({ word: a, count: words[a] }), s), []);
          
      console.log(res);
kind user
  • 40,029
  • 7
  • 67
  • 77
2

Here's a solution using underscore's map function:

words = _.map(words, (v, k) => ({word: k, count: v}));

Underscore's map can iterate over an object. The first parameter to the iteratee is the value and the second parameter is the key.

Gruff Bunny
  • 27,738
  • 10
  • 72
  • 59
0
let object = {
  "06.10 15:00": 3.035,
  "06.10 21:00": 3.001,
};

let arr = [];

for (const [key, value] of Object.entries(object)) {
  arr.push({ date: key, value: value });
}

console.log(arr);
gamerC
  • 29
  • 3