-2

I'm trying to turn an object that I have into and array of objects, I know there must be a simple way of doing this but I cannot seem to figure it out after searching. I'm probably searching the wrong thing.

I've tried pushing to an array but I need each key and value pair to be a separate object in an array.

This is the object that I'm working with:

{ HI: 1,
  undefined: 7,
  MI: 1,
  FL: 1,
  WV: 1,
  TX: 1,
  IA: 3,
  MN: 1,
  MO: 1 }

Not quite sure how to turn each of those values into an object, yes I'm stupid.

the desired output would be [{stateName:'HI' value: 1},{stateName: 'Mi', value: 4},{stateName: 'TX', value: 1}] and so on.

Chameleon
  • 119
  • 1
  • 14
  • Can you show us your current attempt and an example of the desired output? – Calvin Nunes Sep 19 '19 at 19:49
  • @CalvinNunes I added the desired output to the question at the bottom so you can see what I'm meaning. – Chameleon Sep 19 '19 at 19:51
  • 1
    Why would you want an array of objects when each object has different properties? – Barmar Sep 19 '19 at 19:51
  • @Chameleon That's half the requirements, but we'll also need to see your code so we can help you fix it :) Per the rules: *Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error **and the shortest code necessary to reproduce it in the question itself**.* – Tyler Roper Sep 19 '19 at 19:52
  • It might be useful if you wanted something like `[{state: 'HI', value: 1}, {state: 'IA', value: 3}, ...]` – Barmar Sep 19 '19 at 19:52
  • 2
    Are you aware of the `Object.entries` method? – Taplar Sep 19 '19 at 19:52
  • @Barmar There are plenty of use cases for an array of key-value pairs as opposed to an object. For example, any situation where order is important. – Tyler Roper Sep 19 '19 at 19:53
  • @Barmar that is exactly what I want actually. – Chameleon Sep 19 '19 at 19:54
  • I've edited it to explain what I want, I screwed up my first edit. – Chameleon Sep 19 '19 at 19:56
  • 1
    `Object.entries(input).map(([ stateName, value ]) => ({ stateName, value }))` – Mulan Sep 19 '19 at 20:00
  • 1
    @user633183 this works perfectly, thank you. – Chameleon Sep 19 '19 at 20:03

2 Answers2

0

var array = [];

var yourObj = {...}

Object.keys(yourObj).forEach(function(key) {
  var obj = {[key]:obj[key]};
   array.push(obj)
});
Sagar Chaudhary
  • 1,343
  • 7
  • 21
-1

You can do this:

let obj = { HI: 1, undefined: 7, MI: 1,FL: 1,WV: 1,TX: 1,IA: 3,MN: 1,MO: 1 };
let list = [];
for (let name in obj) {
    let item = {};
    item[name] = obj[name];
    list.push(item);
}
CoderCharmander
  • 1,862
  • 10
  • 18