我正在尝试按照以下代码片段过滤非数组 JSON 对象
const filter = { filterRows: ['one'] };
const templateMapper = {
'one': {
title: 'one',
},
'two': {
title: 'two',
},
'three': {
title: 'three',
},
}
const filterDialogView = filter.filterRows;
const filterTemplateMapper = [templateMapper].filter(row => !filterDialogView.includes(row));
console.log(filterTemplateMapper);
但不是过滤
我得到以下输出
[
{
"one": {
"title": "one"
},
"two": {
"title": "two"
},
"three": {
"title": "three"
}
}
]
欲望输出
{
"two": {
"title": "two"
},
"three": {
"title": "three"
}
}
我想根据 filterRows
过滤行,例如如果 filterRows 包含 one
就像上面的 JSON 那么 one
应该从 模板映射器
最佳答案
您可以使用 Object.fromEntries从过滤条目构建对象
这里的想法是:-
- 首先从模板对象中获取条目
- 根据过滤值过滤条目
- 使用 Object.fromEntries 从过滤的条目构建对象
const filter = { filterRows: ['one'] };
const template = {'one': {title: 'one',},'two': {title: 'two',},'three': {title: 'three',}}
const filterDialogView = filter.filterRows;
const final = Object.entries(template).filter(([row])=> !filterDialogView.includes(row))
console.log(Object.fromEntries(final));
如果你的环境不支持 Object.fromEntries 你可以使用这个
const filter = { filterRows: ['one'] };
const template = {'one': {title: 'one',},'two': {title: 'two',},'three': {title: 'three',}}
const filterDialogView = filter.filterRows;
const final = Object.entries(template).filter(([row])=> !filterDialogView.includes(row))
const output = final.reduce((op,[key,value])=>{
op[key] = value
return op
},{})
console.log(output);
关于Javascript 过滤器非数组 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56231883/