如何将MongoDB查询结果重构为指定的对象格式?
解决MongoDB查询结果格式转换问题
嘿,这事儿很简单,用数组的reduce方法就能轻松把你拿到的数组转成想要的键值对格式。我给你写个具体的实现代码:
// 假设从MongoDB查询到的结果存在result变量中 const result = [ { listname: 'ListOne', values: [ { label: 'OptOne', cost: '25' },{ label: 'OptTwo', cost: '22' }] }, { listname: 'ListTwo', values: [ { label: 'OptA', cost: '30' },{ label: 'OptB', cost: '28' }] } ]; // 转换为目标格式 const newData = result.reduce((accumulator, currentItem) => { // 把listname转成小驼峰格式(比如ListOne → listOne) const camelCaseKey = currentItem.listname.charAt(0).toLowerCase() + currentItem.listname.slice(1); // 给累加对象添加键值对 accumulator[camelCaseKey] = currentItem.values; return accumulator; }, {}); console.log(newData); // 输出结果就是你想要的: // { // listOne: [ { label: 'OptOne', cost: '25' }, { label: 'OptTwo', cost: '22' } ], // listTwo: [ { label: 'OptA', cost: '30' }, { label: 'OptB', cost: '28' } ] // }
代码解释
reduce是数组的迭代方法,我们从一个空对象{}开始(也就是第二个参数),逐个处理数组里的每一项- 因为你要的键是小驼峰(
listOne)而不是原数据的大驼峰(ListOne),所以用charAt(0).toLowerCase()把首字母转小写,再拼接后面的字符串 - 如果你的原数据
listname已经是小驼峰格式,那直接用currentItem.listname作为键就行,去掉大小写转换的步骤
额外提醒
如果你的查询结果里有重复的listname,后面的项会覆盖前面的。要是需要合并重复项的values,可以改成这样:
const newData = result.reduce((accumulator, currentItem) => { const camelCaseKey = currentItem.listname.charAt(0).toLowerCase() + currentItem.listname.slice(1); // 若键已存在,合并values;否则直接赋值 accumulator[camelCaseKey] = accumulator[camelCaseKey] ? [...accumulator[camelCaseKey], ...currentItem.values] : currentItem.values; return accumulator; }, {});
内容的提问来源于stack exchange,提问作者McB
相关产品推荐
相关产品推荐

