将嵌套字典中的值转换为字典数组

时间:2014-01-09 18:30:03

标签: javascript

我有一个嵌套字典,如下所示:

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

我想将此字典中的值放入数组中,如下所示:

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

如何将嵌套字典转换为字典数组,其中数组中的每个元素都是原始嵌套字典中的值?

2 个答案:

答案 0 :(得分:2)

将对象中的每个条目都推送到一个数组中。

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将如下所示:

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

您可以看到此in action on jsFiddle

答案 1 :(得分:2)

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