turtle
turtle

Reputation: 8073

Convert values from nested dictionary to an array of dictionaries

I have a nested dictionary that looks like this:

{key1: {"A": 1, "B": 2, "C": 3}, key2: {"A": 2, "B": 2, "C": 2}, ...}

I would like to place the values of from this dictionary into an array, like this:

[{"A": 1, "B": 2, "C": 3}, {"A": 2, "B": 2, "C": 2}, ...]

How can I convert a nested dictionary into an array of dictionaries where each element in the array is the values from the original nested dictionary?

Upvotes: 1

Views: 1029

Answers (2)

Joe Rinehart
Joe Rinehart

Reputation: 763

var stuff = {key1: {"A": 1, "B": 2, "C": 3}, key2: {"A": 2, "B": 2, "C": 2} }
var result = []
for ( var key in stuff ) {
  result.push( stuff[key] )
}

Upvotes: 2

Peter Olson
Peter Olson

Reputation: 142921

Just push every entry in the object into an array.

var obj = {key1: {"A": 1, "B": 2, "C": 3}, key2: {"A": 2, "B": 2, "C": 2}};
var arr = [];
for(var i in obj) {
  if(!obj.hasOwnProperty(i)) continue;
  arr.push(obj[i]);
}

arr will then look like this:

[{"A":1,"B":2,"C":3},{"A":2,"B":2,"C":2}] 

You can see this in action on jsFiddle.

Upvotes: 2

Related Questions