【问题标题】:Convert object to array preserving index将对象转换为数组保留索引
【发布时间】:2015-10-21 10:14:46
【问题描述】:

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

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"]};

【问题讨论】:

    标签: javascript arrays angularjs object multidimensional-array


    【解决方案1】:

    试试看:

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

    【讨论】:

    • 恕我直言,最好将map 替换为each,两者都可以,但使用map 表示您对映射结果感兴趣。所以在以后的代码审查中它可能看起来像一个错误。
    • each 替换map 会产生角度错误:TypeError: Object.keys(...).each is not a function。您使用map 的原始方法可以满足我的需要。所以我会接受答案。但是我没有想到,当我将具有非后续索引的数组插入$location.search(foobar) 以从中生成查询字符串时,它会生成所有应该在提供的索引之前的数组元素为undefined
    • 添加到我之前的评论:当我使用$location.search({"foo1": [3=> 'bar1']})。它返回以下字符串:http://website.com/path?foo1=undefined&foo1=undefined&foo1=bar1。所以我必须重新考虑算法。
    • 啊抱歉应该是forEach我把它和Promise.each混淆了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 2021-11-16
    相关资源
    最近更新 更多