1

I have an object that consists in the number of occurrences for different words. It looks like this :

{
Word1 : 1,
Word2 : 1,
Word3 : 2,
Word4 : 3
}

I would like to have an array that looks like this :

[
{word:Word1, count:1},
{word:Word2, count:1},
{word:Word3, count:2},
{word:Word4, count:3},
]

I looked a bit around and found this code that loops through the object and get the values I want :

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    console.log(key + " -> " + p[key]);
  }
}

I tried to create an empty array and to use push to get the intended values in it, but I don't seem to get the hang of it. I feel like something along those lines should get me the result I want :

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    //Here is where the code should go, something like :
    myNewObject[i].word = key;
    myNewObject[i].count = p[key];
  }
}
1
  • 1
    Shouldn't the last one be word4? Commented Jul 14, 2017 at 14:57

5 Answers 5

5

You can use Object.keys and map:

var obj = {
 Word1 : 1,
 Word2 : 1,
 Word3 : 2,
 Word4 : 3
}

var array = Object.keys(obj).map((key) => ({
  word: key,
  count: obj[key]
}));

console.log(array);

Sign up to request clarification or add additional context in comments.

Comments

0

You can use reduce() on the Object.keys for this:

let o = {
  Word1: 1,
  Word2: 1,
  Word3: 2,
  Word4: 3
};

let arr = Object.keys(o).reduce((a, b) => a.concat({
  word: b,
  count: o[b]
}), []);

console.log(arr);

Comments

0

This should work.

const start = {
  Word1 : 1,
  Word2 : 1,
  Word3 : 2,
  Word4 : 3
};

const finish = Object.keys(start).map(k => { word: k, count: start[k] });

Comments

0

You should push an object for each key in the object:

var result = [];
for (var key in p) {
  if (p.hasOwnProperty(key)) {
    result.push({
      word: key,
      count: p[key]
    });
  }
}

Comments

0

You can use Object.keys() to iterate through each key in the object. Use map() or forEach() to get the desired result.

let o = {
  Word1: 1,
  Word2: 1,
  Word3: 2,
  Word4: 3
};

var result = [];

Object.keys(o).forEach(function(x){
  result.push({word: x, count : o[x]});
});

console.log("Result with forEach :" ,result);

var resultWithMap = Object.keys(o).map( x =>
  ({ word : x, count : o[x] }) );

console.log("Result with map :" , resultWithMap);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.