Home > Software design >  how to get values from an json array
how to get values from an json array

Time:10-13

Guys this might be a simple question, but please help.

i have a data.

var a = { "data":[[1,2,3],[2,4,3],[3,6,7],[1,4],[6,4,3,4],[6,7,3,5]] }

i'm plotting a multiple line chart using chartjs and i want these valus in array to use as datasets. what i wat is to save each array in different var's like;

var a = [1,2,3],
var b = [2,4,3]
var c = [3,6,7]

so that i can pass theese values to chart js and plot chart. any help is appreciated. i thought of foreach and getting by each position. but its not working.

regards

CodePudding user response:

Use Array destructuring.

Use spread operator on last node. That will keep all the remaining nodes except the specified number of paramaters, if you are interested on the frst three nodes only.

var data = { "data": [[1, 2, 3], [2, 4, 3], [3, 6, 7], [1, 4], [6, 4, 3, 4], [6, 7, 3, 5]] }
const [a, b, c, ...restNodes] = data.data;
console.log(a);
console.log(b);
console.log(c);
console.log(restNodes);

Please Note Its not mandatory to have the last node with spread operator. You can pick the first three nodes only using

 const [a, b, c] = data.data;

I just said you can do this aswell

CodePudding user response:

Spread the data and just assign to three variables.

var x = { "data":[[1,2,3],[2,4,3],[3,6,7],[1,4],[6,4,3,4],[6,7,3,5]] }

let [a,b,c] = [...x.data];
console.log(a);
console.log(b);
console.log(c);

There is no need to even include a fourth variable if all you care about is a,b,c.

  • Related