【问题标题】:Using map() or similar function to return the array data in the following format使用 map() 或类似函数以以下格式返回数组数据
【发布时间】:2021-10-08 14:36:51
【问题描述】:

我有以下 javascript 数组(我今天玩得很开心 map()) - 我希望能够返回 pages 数据,但将 page id 作为键和位置的索引pages数组中的那个页面作为值。我做错了什么?

let result = [
  {
      "id": 10000089,
      "units": [
          {
              "id": 10000200,
              "pages": [
                  {
                      "id": 100000882
                  }
              ]
          },
          {
              "id": 10000340,
              "pages": [
                  {
                      "id": 100000912
                  },
                  {
                      "id": 100000915
                  },
                  {
                      "id": 100000919
                  }
              ]
          }
      ],
  }
];
// this is my attempt but doesn't return in the intended format below
result.flatMap(el => el.units.map((e, i) => (e.pages)));

预期输出

pages = [
  100000882 => 0,
  100000912 => 0,
  100000915 => 1,
  100000919 => 2,
]

这里是代码的stackblitz https://stackblitz.com/edit/js-mc9rqe

【问题讨论】:

  • 预期输出无效。 pages 必须是一个对象(或对象数组)。您希望 id 及其索引在各自的 pages 数组中。 .map(i, i) => (e.pages)) 应该如何产生这个输出(你甚至不使用索引i)?

标签: javascript arrays foreach array.prototype.map


【解决方案1】:

您的预期输出应该是object,而不是array。您可以使用Array.prototype.flatMapObject.fromEntries 来实现结果。

let result=[{id:10000089,units:[{id:10000200,pages:[{id:100000882}]},{id:10000340,pages:[{id:100000912},{id:100000915},{id:100000919}]}]}];

const pages = Object.fromEntries(
  result.flatMap(item => item.units.flatMap(unit => unit.pages.map((page,i) => ([page.id, i]))))
);
console.log(pages);

请注意Object.fromEntries() 采用 [key, value] 对的数组,然后将它们转换为对象。在您的情况下,page.id 将是 key,而最后一张地图的 index 将是 value

【讨论】:

    【解决方案2】:

    在您的数据中,pages 也是一个对象数组。因此,您还需要遍历每个页面。

    • 使用Array.flat

    let result=[{id:10000089,units:[{id:10000200,pages:[{id:100000882}]},{id:10000340,pages:[{id:100000912},{id:100000915},{id:100000919}]}]}];
    
    const getFormattedData = data => {
      const res = data.map(datum => datum.units.map(unit => unit.pages.map(({ id }, i) => ({
        [id]: i
      }))));
      return res.flat(2);
    }
    console.log(getFormattedData(result));
    • 使用Array.flatMap

    let result=[{id:10000089,units:[{id:10000200,pages:[{id:100000882}]},{id:10000340,pages:[{id:100000912},{id:100000915},{id:100000919}]}]}];
    
    const getFormattedData = data => {
      return data.flatMap(datum => datum.units.flatMap(unit => unit.pages.map(({ id }, i) => ({
        [id]: i
      }))));
    }
    console.log(getFormattedData(result));

    请注意,以上两种方法都会产生对象数组。

    【讨论】:

      猜你喜欢
      • 2014-09-03
      • 1970-01-01
      • 2011-06-11
      • 2019-06-09
      • 2017-04-04
      • 2017-02-24
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多