John Vi
John Vi

Reputation: 23

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 ]

?

Upvotes: 0

Views: 62

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386540

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; }

Upvotes: 1

Related Questions