我有数组对的JSON对象,如下所示:
Object {x:Array [36159],y:Array [36159],year:Array [36159]}
小样本例如:
{
"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]
}
我想在一年内过滤这个对象。如果JSON数据是数组或键,值对,我可以使用过滤器:
data.filter(function (x) {
return x.year == 1991
});
但由于JSON结构是平面数组,我不知道如何处理。
期望的结果是:
{
"x": [309339618361.619, 102862032084.12102],
"y": [13950252.45052416, 1158787.402385158],
"year": [1991, 1991]
}
答案 0 :(得分:3)
你可以使用带有比较的回调和属性的数组,你想要应用过滤器。
Generic
答案 1 :(得分:2)
您可以使用reduce()
并按要过滤的年份索引添加值。
var obj = {
"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]
}
var result = obj.year.reduce(function(r, e, i) {
if (e == 1991) {
r.x = (r.x || []).concat(obj.x[i]);
r.y = (r.y || []).concat(obj.y[i]);
r.year = (r.year || []).concat(obj.year[i])
}
return r;
}, {});
console.log(result)

答案 2 :(得分:0)
只需复制obj
并迭代year
属性的元素,然后删除不等于1991
的元素。
var obj = {
x: [309339618361.619, 102862032084.12102],
y: [13950252.45052416, 1158787.402385158],
year: [1991, 1991]
},
scan = {};
Object.assign(scan, obj);
for(var i = 0, len = scan.year.length; i < len; i ++) {
if(scan.year[i] !== 1991) {
scan.year.splice(i, 1);
}
}
console.log(scan);