0

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

0

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.