简体   繁体   中英

how to get values from an json array

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

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

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 .

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