【发布时间】:2020-01-23 17:54:39
【问题描述】:
我有一些 JSON 数据,我试图过滤掉没有特定属性的 JSON 对象。
我可以使用filter function from Underscore.JS 成功过滤掉不具有正确属性的对象。
但是,当过滤器函数运行时,它会剥离对象的键名。
下面是过滤函数中变量data中使用的JSON:
{
"Presentations": {
"Instant": false,
"Daily": false,
"WeeklySummary": false,
"ContentTypeId": 5
},
"Articles": {
"Instant": true,
"Daily": false,
"WeeklySummary": true,
"ContentTypeId": 1
},
"Blogs": {
"Instant": true,
"Daily": false,
"WeeklySummary": true,
"ContentTypeId": 61
},
"NewsBriefs": {
"Instant": false,
"Daily": false,
"WeeklySummary": false,
"ContentTypeId": 2
},
"SpecialInsights": {
"Instant": false,
"Daily": false,
"WeeklySummary": false,
"ContentTypeId": 50
},
"UserSelected": {
"Frequency": null,
"Value": false,
"ContentTypeId": 0
}
}
这是一个 JavaScript 过滤器函数,它返回一个必须包含 'Instant' 属性的对象数组
newArr = _.filter(data, function(obj){
return obj.hasOwnProperty('Instant')
});
如果我控制台记录 newArr,这就是我得到的:
[
{
"Instant":false,
"Daily":false,
"WeeklySummary":false,
"ContentTypeId":5
},
{
"Instant":true,
"Daily":false,
"WeeklySummary":true,
"ContentTypeId":1
},
{
"Instant":true,
"Daily":false,
"WeeklySummary":true,
"ContentTypeId":61
},
{
"Instant":false,
"Daily":false,
"WeeklySummary":false,
"ContentTypeId":2
},
{
"Instant":false,
"Daily":false,
"WeeklySummary":false,
"ContentTypeId":50
}
]
如您所见,它正确地过滤掉了不具有Instant 属性的对象,在本例中为UserSelected 对象。
但是,在该过程中,我丢失了对象键名称,例如 Presentations 和 Articles。
过滤 JSON 数据时如何保留这些键名?
【问题讨论】:
-
请同时添加想要的结果。
-
您好,如果您愿意,我可以添加。输出将与 newArr 相同,但我们保留了原始 JSON 中的那些键名。我只是不想添加重复的代码和混淆问题。
标签: javascript json underscore.js