vedar vedar - 5 months ago 11
JSON Question

Filter JSON object with flat arrays

I have JSON object with array pairs, like this:


Object {x: Array[36159], y: Array[36159], year: Array[36159]}


Small sample as example:

{
"x": [309339618361.619, 102862032084.12102, 72892839276.09761, 46463392384.54194, -39360182208.042145],
"y": [13950252.45052416, 1158787.402385158, -4368238.261400843, 1339913.7393283844, 2085336.6277048483],
"year": [1991, 1991, 1992, 1992, 1992]
}


I want to filter this object on year. If JSON data was array or key, value pairs, I could have used filter:

data.filter(function (x) {
return x.year == 1991
});


but as JSON structure is pairs of flat arrays, I have no idea how to approach.




Desired results is this:

{
"x": [309339618361.619, 102862032084.12102],
"y": [13950252.45052416, 1158787.402385158],
"year": [1991, 1991]
}

Answer

You could use a callback with the comparison and an array for the properties, you want apply the filter on.

var object = {
        "x": [309339618361.619, 102862032084.12102, 72892839276.09761, 46463392384.54194, -39360182208.042145],
        "y": [13950252.45052416, 1158787.402385158, -4368238.261400843, 1339913.7393283844, 2085336.6277048483],
        "year": [1991, 1991, 1992, 1992, 1992]
    },
    result = {};

['x', 'y', 'year'].forEach(function (p) {
    result[p] = object[p].filter(function (a, i) {
        return object.year[i] === 1991;
    });
});

console.log(result);

Comments