【问题标题】:How to transform an object into an array of objects without using jQuery?如何在不使用 jQuery 的情况下将对象转换为对象数组?
【发布时间】:2016-09-20 13:03:33
【问题描述】:

我怎样才能把这个对象转换成一个里面有对象的数组?

beacons = {
    "key": {
        "one": "char",
        "two": "sue",
        "three": "johnny"
    },
    "key2": {
        "one": "char",
        "two": "sue",
        "three": "johnny"
    },
    "key3": {
        "one": "char",
        "two": "cara",
        "three": "johnny"
    }
}

结果应该类似于下面的结果,我应该以这样的方式调用属性:beaconsArray[1].one ---> "char"

beaconsArray = [{
    "one": "char",
    "two": "sue",
    "three": "johnny"
}, {
    "one": "char",
    "two": "sue",
    "three": "johnny"
}, {
    "one": "char",
    "two": "sue",
    "three": "johnny"
}]

【问题讨论】:

标签: javascript arrays object transform


【解决方案1】:

var beacons = {
"key": { "one": "char", "two": "sue", "three": "johnny" }, "key2": { "one": "char", "two": "sue", "three": "johnny" }, "key3": { "one": "char", "two": "cara", "three": "johnny" }
};

var beaconsArray = [];
for(var key in beacons) {
 beaconsArray.push(beacons[key]);
}

console.log(beaconsArray);

【讨论】:

    【解决方案2】:

    您可以使用单个 Array#map 进行迭代。

    为了获得稳定的结果,您可能需要事先对键进行排序。

    var beacons = { "key": { "one": "char", "two": "sue", "three": "johnny" }, "key2": { "one": "char", "two": "sue", "three": "johnny" }, "key3": { "one": "char", "two": "cara", "three": "johnny" } },
        array = Object.keys(beacons).sort().map(function (k) { return beacons[k]; });
    
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 如果 SE 愿意 finally get around to doing this 那就太好了,这样你就不必拥有那个 CSS...
    • 对,控制台用css有点可惜,最好是带句柄的动态大小。
    • 我认为即使没有 css,这段代码也非常有用。谢谢@NinaScholz =D
    • @GonzaloDiazAilan:是的。 CSS 只是为了让控制台填充结果窗格,因为几个月后,SE 仍然没有为控制台选项添加 UI。
    【解决方案3】:

    类似这样的:

    var beacons = { "key": { "one": "char", "two": "sue", "three": "johnny" }, "key2": { "one": "char", "two": "sue", "three": "johnny" }, "key3": { "one": "char", "two": "cara", "three": "johnny" } }
    var result = [];
    
    for (key in beacons) {
      result.push(beacons[key]);
    }
    
    console.log(result);
    

    【讨论】:

      【解决方案4】:

      Object.values 会为你做这件事。

      var beaconsArray = Object.values(beacons);
      

      请务必注意,这还不是 JS 规范的正式部分,因此浏览器支持非常有限。 不要在没有polyfill 的情况下依赖它,除非您确定您的用户将使用最新版本的 Chrome 或 Firefox。

      【讨论】:

      • 我得到“Object.values 不是函数(…)”。我不知道为什么。它的文档似乎几乎是我想要的 =O
      • @T.J.Crowder:哎呀,太习惯了转译器,那是我的错!将编辑!
      • @GonzaloDiazAilan:正如 TJ Crowder 所说,这还不是一个标准化的功能——新版本的 Chrome 和 Firefox 实现了它,但仅此而已。
      猜你喜欢
      • 2020-08-23
      • 2019-05-03
      • 2020-05-11
      • 1970-01-01
      • 2022-01-23
      • 2014-05-02
      • 1970-01-01
      • 2018-02-13
      相关资源
      最近更新 更多