繁体   English   中英

如何在 NodeJs 中删除 TextRow 并将字符串添加到 JSON

[英]How to remove TextRow and add a string to JSON in NodeJs

我想删除 TextRow 并向 NodeJs 中的 JSON 添加一个字符串( true )。 我在我的代码下面添加了。

Node.js 代码:

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})
}

group数据:

[
  TextRow { name: '/products', email: '111@gmail.com' },
  TextRow { name: '/products', email: '222@gmail.com' },
  TextRow { name: '/sales', email: '111@gmail.com' },
  TextRow { name: '/sales', email: '222@gmail.com' },
  TextRow { name: '/sales', email: '333@gmail.com' },
  TextRow { name: '/sales', email: '444@gmail.com' },
  TextRow { name: '/finance', email: '333@gmail.com' },
  TextRow { name: '/finance', email: '444@gmail.com' },
]

我的 output:

{
  '/products': [
    TextRow { name: '/products', email: '111@gmail.com' },
    TextRow { name: '/products', email: '222@gmail.com' },
  ],
  '/sales': [
    TextRow { name: '/products', email: '111@gmail.com' },
    TextRow { name: '/products', email: '222@gmail.com' },
    TextRow { name: '/products', email: '333@gmail.com' },
    TextRow { name: '/products', email: '444@gmail.com' },
  ],
  '/products': [
    TextRow { name: '/products', email: '333@gmail.com' },
    TextRow { name: '/products', email: '444@gmail.com' },
  ],
}

Output 应该是:

{
  '/products': [
    {
      '111@gmail.com': true,
      '222@gmail.com': true,
    }
  ],
  '/sales': [
    {
      '111@gmail.com': true,
      '222@gmail.com': true,
      '333@gmail.com': true,
      '444@gmail.com': true,
    }
  ],
  '/finance': [
    {
      '333@gmail.com': true,
      '444@gmail.com': true,
    }
  ]
}

与其推送整行,不如创建一个新的 object。 我不太清楚为什么你的最终 output 是一个具有单个 object 的数组,或者为什么每个 email 都有一个true

const key = obj[property];
if (!acc[key]) {
  acc[key] = [{}];
}
acc[key][0][obj.email] = true;
return acc;

这样做会产生一个 object,其键是name ,值是一个数组,每个数组都有一个 object,其键是 email 地址。

这是一个关于你应该如何做的例子。 它会给你预期的结果

 const list = [{ TextRow: { name: '/products', email: '111@gmail.com' } }, { TextRow: { name: '/products', email: '222@gmail.com' } }, { TextRow: { name: '/sales', email: '111@gmail.com' } }, { TextRow: { name: '/sales', email: '222@gmail.com' } }, { TextRow: { name: '/sales', email: '333@gmail.com' } }, { TextRow: { name: '/sales', email: '444@gmail.com' } }, { TextRow: { name: '/finance', email: '333@gmail.com' } }, { TextRow: { name: '/finance', email: '444@gmail.com' } }, ] const result = list.reduce((acc, x) => { const name = x['TextRow']['name']; const obj = { [x['TextRow'].email]: true }; if (acc[name]) { acc[name].push(obj) } else { acc[name] = [obj]; } return acc; }, []) console.log(result)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM