首页 > 解决方案 > 为解析器塑造数据

问题描述

本质上,这个解析器返回一个引号列表,它可以来自存储在 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

标签: javascriptarraysjsonobjectmongoose

解决方案


我想你只想使用.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);
    },
  });
}

推荐阅读