javascript - 为解析器塑造数据
问题描述
本质上,这个解析器返回一个引号列表,它可以来自存储在 mongo db 中的不同书籍。这是db的结构!
getQuotes: async () => {
const getQuotes = await booksModel.find({}, "quotes");
console.log(getQuotes);
// #1
for (const element of getQuotes) {
const test = element.quotes;
console.log(test)
// #2
Object.values(test).forEach((val) => {
console.log(val);
// #3
return val;
});
}
},
它返回的东西与数据需要的形状非常相似......
这是console.log #3!
{
book: 1,
page: 12,
excerpt: 'asaaaad',
comment: 'asd',
_id: 'N_YOT_Gms_fvAqQKL3Y23'
}
{
book: 1,
page: 12,
excerpt: 'sdfsdfsdfsdf',
comment: 'asd',
_id: 'QP5iLh3Gj2X8ZcSN7hoPF'
}
{
book: 2,
page: 12,
excerpt: 'asaasdasdaad',
comment: 'asd',
_id: '2kdkfgW6MERwGtvbXph9e'
}
这是console.log #2!
[
{
book: 1,
page: 12,
excerpt: 'asaaaad',
comment: 'asd',
_id: 'N_YOT_Gms_fvAqQKL3Y23'
},
{
book: 1,
page: 12,
excerpt: 'sdfsdfsdfsdf',
comment: 'asd',
_id: 'QP5iLh3Gj2X8ZcSN7hoPF'
}
]
[
{
book: 2,
page: 12,
excerpt: 'asaasdasdaad',
comment: 'asd',
_id: '2kdkfgW6MERwGtvbXph9e'
}
]
这是console.log #1!
[
{ _id: 'leO68YLuG_mG4KS491Kpz', quotes: [ [Object], [Object] ] },
{ _id: 'ymbUWql0sREAKuaVXZ_KY', quotes: [ [Object] ] }
]
除了我被困在 forEach 中并且无法为我的 graphql 解析器构建一个漂亮的数组。我想知道还有其他人会如何处理这个来改善我的观点?自从我拿起这个已经过去了一年左右,所以不要太介意我;我做了大部分工作(好吧,我试过了):p
解决方案
我想你只想使用.flatMap
:
getQuotes: async () => {
const quotes = await booksModel.find({}, "quotes");
return quotes.flatMap((el) => el.quotes);
}
const quotes = [{
_id: 'leO68YLuG_mG4KS491Kpz',
quotes: [{
book: 1,
page: 12,
excerpt: 'asaaaad',
comment: 'asd',
_id: 'N_YOT_Gms_fvAqQKL3Y23'
}, {
book: 1,
page: 12,
excerpt: 'sdfsdfsdfsdf',
comment: 'asd',
_id: 'QP5iLh3Gj2X8ZcSN7hoPF'
}],
}, {
_id: 'ymbUWql0sREAKuaVXZ_KY',
quotes: [{
book: 2,
page: 12,
excerpt: 'asaasdasdaad',
comment: 'asd',
_id: '2kdkfgW6MERwGtvbXph9e'
}]
}];
console.log(quotes.flatMap((el) => el.quotes));
如果你的环境不支持它(这是一个新的 js 功能),那就做
if (!Array.prototype.flatMap) {
Object.defineProperty(Array.prototype, 'flatMap', {
configurable: true,
writable: true,
value: function () {
return Array.prototype.map.apply(this, arguments).flat(1);
},
});
}
推荐阅读
- google-maps - Flutter Google Maps 应用程序在浏览器中引发异常和崩溃,但在 Android 上却没有
- javascript - Javascript,Jquery 3 - 先运行获取请求
- ios - 按字母顺序排序 NSFetchedResultsController 项目,但优先考虑 Swift 和 Coredata 中的特定项目
- selenium - 选择器仅在检查/选择元素(硒)后工作
- text-to-speech - Google Assistant 的其他 WaveNet 语音
- amazon-web-services - 在 CloudFormation 模板中使用现有角色
- angular - 使用 fromEvent 测试组件单击带有 Angular 的文档
- javascript - 如何在innerhtml中传递字符串参数
- mysql - Sequelize:排除列值为空的 LEFT JOIN
- python - 数据库只读设置未从子文件夹中的 conftest.py 加载