按键和其项过滤对象

3

我有一个对象,想要筛选它的键。

我想按照ID来筛选对象,代码如下:

let myKeys = Object.keys(data).filter(function(key) {
        //console.log(data[key]);
        if(parseInt(key) === parseInt(vm.system_id)) {
            return data[key];
        }
    });

    console.log(myKeys);

这个方案还有一定的效果 - 我得到了关键内容,但是我没有获取筛选出来的项下的所有数据/物品。

我要筛选的对象与这个对象类似:

{
"646": [{
        "id": 52144,
        "timestamp": "2017-08-17T14:10:23Z",
        "type": "alarm",
        "code": 210,
        "title": "",
        "description": "",
        "remedy": "",
        "appeared": "2017-08-17T14:10:09Z",
        "disappeared": null,
        "acknowlegded": null,
        "solved": null,
        "system_name": "CG-MX19D7K5C1",
        "system_id": 646,
        "system_device_id": 458,
        "stream": "cu351.alarm_code"
    }
],
"693": [{
        "id": 51675,
        "timestamp": "2017-08-16T13:59:55Z",
        "type": "alarm",
        "code": 215,
        "title": "",
        "description": "",
        "remedy": "",
        "appeared": "2017-08-16T13:59:57Z",
        "disappeared": null,
        "acknowlegded": null,
        "solved": null,
        "system_name": "Demo 07122016",
        "system_id": 693,
        "system_device_id": 371,
        "stream": "cu351.alarm_code"
    }, {
        "id": 51677,
        "timestamp": "2017-08-16T13:59:57Z",
        "type": "alarm",
        "code": 214,
        "title": "",
        "description": "",
        "remedy": "",
        "appeared": "2017-08-16T13:59:59Z",
        "disappeared": null,
        "acknowlegded": null,
        "solved": null,
        "system_name": "Demo 07122016",
        "system_id": 693,
        "system_device_id": 371,
        "stream": "cu351.alarm_code"
    }
]

}

1个回答

6

Array#filter 期望返回布尔值,你可以使用以下代码:

let myKeys = Object.keys(data).filter(key => key == vm.system_id);

为了获取键并以给定的键渲染新对象, 您可以使用以下代码:

要在单个数组中获取所有项目, 您可以使用以下代码进行收集:

let result = myKeys.reduce((r, k) => r.concat(data[k]), []);

不太对,这仍然只返回一个带有键['693']的数组 - 但没有给我该项下的所有数据。 - hauge
对的,你需要另一个循环,请添加一个示例和你的期望。 - Nina Scholz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接