从javascript对象创建数组

问题描述 投票:0回答:3

我有一个像这样的JavaScript对象

server1:[38,1,2,7]
server2:[6,2,1,4
server3:[160,30,21,20]

我想在这样的数组中插入这些对象的元素

data1=[
  [
    {name:"Success", y:38},
    {name:"Failure", y:1},
    {name:"Aborted", y:2},
    {name:"Unstable", y:7}
  ],
  [
    {name:"Success", y:6},
    {name:"Failure", y:2},
    {name:"Aborted", y:1},
    {name:"Unstable", y:4}
  ],
  [
    {name:"Success", y:160},
    {name:"Failure", y:30},
    {name:"Aborted", y:21},
    {name:"Unstable", y:20}
  ]
]

JavaScript对象的键的第一个元素是成功,第二个元素是失败,第三个元素是不稳定的,第四个元素是中止的。我有什么方法可以做到这一点?任何帮助将不胜感激

javascript highcharts
3个回答
5
投票

您可以使用Object.values方法获取对象值,并使用Array#map方法生成数组。

const data = {
  server1: [38, 1, 2, 7],
  server2: [6, 2, 1, 4],
  server3: [160, 30, 21, 20]
}


let res = Object.values(data).map(([s, f, a, u]) => [{
    name: "Success",
    y: s
  },
  {
    name: "Failure",
    y: f
  },
  {
    name: "Aborted",
    y: a
  },
  {
    name: "Unstable",
    y: u
  }
])

console.log(res);

1
投票

您可以为名称获取数组并映射外部和内部值。

var server1 = [38, 1, 2, 7],
    server2 = [6, 2, 1, 4],
    server3 = [160, 30, 21, 20],
    names = ["Success", "Failure", "Aborted", "Unstable"],
    result = [server1, server2, server3]
        .map(s => names.map((name, i) => ({ name, y: s[i] })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

0
投票

如果你喜欢良好的ol'循环而不是功能map()方法,请使用:

var test = {
    server1: [38, 1, 2, 7],
    server2: [6, 2, 1, 4],
    server3: [160, 30, 21, 20]
};

function makeArray(input) {
    var array = [];
    for (var server in input) {
        array.push([
            {name: "Success", y : input[server][0]},
            {name: "Failure", y : input[server][1]},
            {name: "Aborted", y : input[server][2]},
            {name: "Unstable", y : input[server][3]},
        ]);
    }
    return array;
}

console.log(makeArray(test));
.as-console-wrapper { max-height: 100% !important; top: 0; }
© www.soinside.com 2019 - 2024. All rights reserved.