我正在尝试从JSON数组中选择某些键,然后过滤其余键。
var json = JSON.stringify(body);
这是:
{
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
},
"more keys": "foo",
"unwanted key": "foo"
}
我想要吗:
{
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
}
}
我已经签出How to filter JSON data in node.js?,但我希望不带任何包装。
答案 0 :(得分:1)
您需要先将obj过滤,然后再将其传递给json stringify:
const rawJson = {
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
},
"more keys": "foo",
"unwanted key": "foo"
};
// This array will serve as a whitelist to select keys you want to keep in rawJson
const filterArray = [
"FirstName",
"typeform_form_submits",
];
// this function filters source keys (one level deep) according to whitelist
function filterObj(source, whiteList) {
const res = {};
// iterate over each keys of source
Object.keys(source).forEach((key) => {
// if whiteList contains the current key, add this key to res
if (whiteList.indexOf(key) !== -1) {
res[key] = source[key];
}
});
return res;
}
// outputs the desired result
console.log(JSON.stringify(filterObj(rawJson, filterArray)));
答案 1 :(得分:0)
var raw = {
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
},
"more keys": "foo",
"unwanted key": "foo"
}
var wantedKeys =["FirstName","typeform_form_submits" ]
var opObj = {}
Object.keys(raw).forEach( key => {
if(wantedKeys.includes(key)){
opObj[key] = raw[key]
}
})
console.log(JSON.stringify(opObj))
答案 2 :(得分:0)
现在您可以像这样使用Object.fromEntries
:
Object.fromEntries(Object.entries(raw).filter(([key]) => wantedKeys.includes(key)))
答案 3 :(得分:0)
我知道这个问题被问到了,但是我只想扔在那里,因为没有其他人这样做:
如果您受约束并决心使用stringify
来执行此操作,那么它的鲜为人知的功能之一就是replacer
,它是第二个参数。例如:
// Creating a demo data set
let dataToReduce = {a:1, b:2, c:3, d:4, e:5};
console.log('Demo data:', dataToReduce);
// Providing an array to reduce the results down to only those specified.
let reducedData = JSON.stringify(dataToReduce, ['a','c','e']);
console.log('Using [reducer] as an array of IDs:', reducedData);
// Running a function against the key/value pairs to reduce the results down to those desired.
let processedData = JSON.stringify(dataToReduce, (key, value) => (value%2 === 0) ? undefined: value);
console.log('Using [reducer] as an operation on the values:', processedData);
// And, of course, restoring them back to their original object format:
console.log('Restoration of the results:', '\nreducedData:', JSON.parse(reducedData), '\nprocessedData:', JSON.parse(processedData));
在以上代码段中,键值对仅使用stringify
进行过滤:
.parse()
)。现在,我要强调的是,如果只是出于晦涩的原因,我不主张将其作为减少对象的适当方法(尽管它会生成所述对象的完整SHALLOW副本,并且实际上表现出令人惊讶的性能)。从可读性的角度来看,它是添加到武器库中的完全有效的(并且是主流;也就是说,它内置在语言中,而不是hack)。