将对象转换为数组保留索引

时间:2015-10-21 10:14:47

标签: javascript arrays angularjs object multidimensional-array

我有一个多维对象。我需要转换为数组的嵌套对象,我这样做:

var foobar = {"foo1": { "5": "bar1", "8": "bar2" }, "foo2": { "3": "bar8", "5": "bar9" }};

angular.forEach(foobar, function(value, key) {
    if (angular.isObject(value)) {
        var arr = Object.keys(value).map(function(k) { return value[k]; });
        foobar[key] = arr;
    }
});

console.log(foobar);

{"foo1": ["bar1", "bar2"], "foo2": ["bar8", "bar9"]};

如何将对象转换为数组保留索引,使其如下所示:

{"foo1": [5 => "bar1", 8 => "bar2"], "foo2": [3 => "bar8", 5 => "bar9"]};

1 个答案:

答案 0 :(得分:2)

试试:

angular.forEach(foobar, function(value, key) {
  if (angular.isObject(value)) {
    var arrValue = [];
    Object.keys(value).forEach(function(k) { arrValue[k] = value[k]; });
    foobar[key] = arrValue;
  }
});