简体   繁体   中英

Combine 2 array into json with different sizes

I have 2 arrays in the below:

sonuc_X = [ 41.01766, 41.01746, 41.05877, 41.05974, 41.04383, 41.03693 ];
var labels = ["lat"];

I also have merge processing below:

var obj_X = {};
    for (var j = 0; j < labels.length; j++) {
        obj_X[labels[j]] = sonuc_X[j];
    }
var asJSON = JSON.stringify(obj_X);
    console.log(asJSON);

when I combine two sequences at the json, the following result comes out:

{"lat":41.01766}

I expect:

[ "lat":41.01766, "lat":41.01746, "lat":41.05877, "lat":41.05974, "lat":41.04383, "lat":41.03693 ]

?

You could iterate the data and build new objects with the wanted keys.

 var data = [41.01766, 41.01746, 41.05877, 41.05974, 41.04383, 41.03693], keys = ["lat", "lng"], result = data.reduce(function (r, v, i) { if (i % keys.length === 0) { r.push({}); } r[r.length - 1][keys[i % keys.length]] = v; return r; }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

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