Javascript Json

Asked

Viewed 41 times

1

Hello folks I need to assemble an object of this kind:

{y: "2017-8", a: 0, b: 0, c: 2, d: 0, …}

The lyrics go up to h, but can vary from one user to another, I’m putting together a line chart Morris.Line. My server returns an array to me:

["a: 0", "b: 1", "c: 0", "d: 0"]

If I put this with toString() I get:

console.log(x);
a: 0,b: 1,c: 0,d: 0

Apparently perfect but, it doesn’t solve my problem because if I put inside the object that I need to initialize to make my graphic I get:

console.log({y: data, x});
{y: "2017-8", x: "a: 0,b: 1,c: 0,d: 0"}

If I put the direct array is also not as needed; I get:

console.log({y: data, x});
{y: "2017-8", x: Array(4)}

Good guys like I do to get what I put there in the beginning ?

2 answers

1


It would be something like that:

a = ["a: 0", "b: 1", "c: 0", "d: 0"];
obj = {};
obj['y'] = '2017-8';
a.forEach(function(el, i){
    var arr = el.split(': ');
    obj[arr[0]] = arr[1];
});
console.log(obj);

{y: "2017-8", a: "0", b: "1", c: "0", d: "0"}

0

For "code golfing" purposes:D

let arrayDoServer = ["a: 0", "b: 1", "c: 0", "d: 0"];
let jsonDeSaida   = JSON.parse('{"' + arrayDoServer.join('","').replace(/: /g, '":"') + '"}');
console.log(jsonDeSaida);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.