简体   繁体   中英

Transform a single object into an array of objects

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];
  }
}

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); 

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); 

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] });

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]
    });
  }
}

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM