我有一个像这样的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对象的键的第一个元素是成功,第二个元素是失败,第三个元素是不稳定的,第四个元素被中止。有什么办法可以做到这一点?任何帮助将不胜感激
答案 0 :(得分: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 :(得分: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; }
答案 2 :(得分:0)
如果您比功能map()方法更喜欢良好的ol'循环,请使用以下方法:
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; }