Javascript 过滤器非数组 JSON 对象

标签 javascript node.js json filter

我正在尝试按照以下代码片段过滤非数组 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/

相关文章:

javascript - bxslider 稍微切断图像

javascript - 仅用于背景图像的 CSS3 过渡

json - IntelliJ IDEA 如何正确地将 $NODE_DEBUG_OPTION 传递给 npm-run-all

java - Spring MVC 3 -> 验证

javascript - 点数不显示时,如何将菜单按钮变成白色?

javascript - 如何让这些 html 元素正确定位和交错?

node.js - 在 res.send 期间更改了 JS 对象

node.js - 优雅关闭 Node expressjs不起作用

c# - 将嵌套的 JSON 数据解析为 DataTable

javascript - 如何从 WCF 服务使用 JSON