-2

My object looks like this { {},{},{},{} }

I want it to look like this:

[ {},{},{},{} ]

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Marco Cano
  • 367
  • 1
  • 4
  • 18
  • 2
    Do you want to loose the property names for the inner objects in the original object? Because the original object cannot be the way you described. It has to be `{foo:{}, bar:{}, baz:{}}`. – Gerardo Furtado Jun 03 '17 at 03:50
  • 1
    where are the keys for your original object? – mugabits Jun 03 '17 at 03:52

4 Answers4

2

IF you are on Chrome or Firefox only, you can use Object.values():

var o = {a:{k:1}, b:{k:2}, c:{k:3}}
var values = Object.values(o);
// [{"k":1}, {"k":2}, {"k":3}]

Otherwise, use (and accept) an answer based on Object.keys().

Phrogz
  • 296,393
  • 112
  • 651
  • 745
1

Well, first of all there is no such thing as an object of objects unless you mean an object which properties are objects. Example: { foo: { bar: 'xyz'} }.

To convert such object into a collection (array of objects) just loop through the keys like such

let objOfObjs = {
  foo: { xyz: 'bar'},
  bar: { abc: 'foo'}
}, collection = [];

Object.keys(objOfObjs).forEach(key => collection.push(objOfObjs[key]));

console.log(collection); //[ { xyz: 'bar' }, { abc: 'foo' } ]

Repl: https://repl.it/I4MS

Baruch
  • 2,381
  • 1
  • 17
  • 29
  • 1
    `collection = Object.keys (objOfObjs).map (key => objOfObjs[key]);` ? – HBP Jun 03 '17 at 03:56
  • @HBP True, I rather do it the way I posted simply because I don't like doing that sort of logic in variable declarations. – Baruch Jun 03 '17 at 03:57
1
var obj = { 'a' : {}, 'b': {}, 'c': {}, 'd': {} }
var list = [];
Object.keys(obj).forEach(function(key) {
    list.push(obj[key]);
});

or simpler

   var list = Object.values(obj);
mugabits
  • 1,015
  • 1
  • 12
  • 22
0

If you're using jQuery, you can use the $.each() method to loop through the original object.

Otherwise, you can try a for loop:

var originalObject = { 
    "key1": { "obj1Key": "obj1Value" },
    "key2": { "obj2Key": "obj2Value" },
    "key3": { "obj3Key": "obj3Value" } 
}

var newArray = [];

for (var key in originalObject) {
    newArray.push(originalObject[key]);
}

console.log("New Array: " + newArray);
Bobby Speirs
  • 667
  • 2
  • 7
  • 14