简体   繁体   中英

Creating array from javascript object

I have a JavaScript object like this

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

I want to insert the elements of this objects in an array like this

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

The first element of the key of JavaScript object is success, second element is failure, third element is unstable and fourth element is aborted.Is there any way I can do this? Any help will be appreciated

You can use Object.values method to get object values and use Array#map method to generate the array.

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

You could take an array for the names and map the outer and inner values.

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

If you prefer good ol' loops over functional map() approach, use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM