Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split object into two properties [duplicate]

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!

like image 248
Matt Avatar asked Dec 04 '22 21:12

Matt


1 Answers

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)
like image 173
Nenad Vracar Avatar answered Dec 06 '22 10:12

Nenad Vracar