简体   繁体   中英

How to add an Array to an Javascript Object

I have the following code:

var optionsChart = {
    data: [{
        type: "bla",
        dataPoints: [{
            x: 1,
            y: 3
        }, {
            x: 1,
            y: 2
        }, {
            x: 3,
            y: 4
        }]
    },
    etc...
}

Now I tried to generate the Datas in the dataPoints field dynamically. I have an Array like this:

dataArray = [[1,3], [1,2],[3,4]];

I try to insert his after dataPoints , but when doing this it needs to be exactly like in the code above, but I don't know how to do that.

Any suggestions here? Thank you very much!

You need to do this way:

optionsChart.data[0].dataPoints.push(dataArray.map(function (obj) {
    return {
        x: obj[0],
        y: obj[1]
    };
}));

Or try this way:

optionsChart.data[0].dataPoints = dataArray.map(function (obj) {
    return {
        x: obj[0],
        y: obj[1]
    };
});

Here you go :

optionsChart.data[0].dataPoints.push(dataArray.map(function(t) {
         return {x: t[0], y: t[1]};
}));

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