我有一些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')
});
如果我用console.log记录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数据时如何保留这些键名?
答案 0 :(得分:4)
您可以在没有任何库的情况下做到这一点:
Object.entries(data).filter(([key, value]) => {
return value.hasOwnProperty('Instant')
}).reduce((acc, [key, value]) => {
return { ...acc, [key]: value }
}, {})
您做错的是,您仅在遍历字典时保留值,而从未保留键。我猜您也可以使用新的fromEntries
,但其工作方式相同