如何在不使用jQuery的情况下将对象转换为对象数组?

时间:2016-09-20 13:03:33

标签: javascript arrays object transform

如何将此对象转换为包含对象的数组?

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 ---> "炭"

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

4 个答案:

答案 0 :(得分:2)

#include "stdafx.h"

#pragma comment(lib, "cryptopp.lib)

using namespace CryptoPP;

int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}

答案 1 :(得分: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; }

答案 2 :(得分: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 result = [];

for (key in beacons) {
  result.push(beacons[key]);
}

console.log(result);

答案 3 :(得分:0)

Object.values会为你做这件事。

{{1}}

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