Javascript Json

1

Hello everyone, I need to mount an object of this type:

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

The letters go up to h, but may vary from one user to another, I'm putting together a graph Morris.Line line. My server returns an array:

["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

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

If I put the array straight, it does not stay as accurate; I get:

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

Well, how do I get what I put there in the beginning?

    
asked by anonymous 15.09.2017 / 01:57

2 answers

1

It would look something like this:

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"}
    
15.09.2017 / 02:35
0

For golfing purposes: D

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