简体   繁体   English

map方法里面的两个map方法

[英]Two map methods inside map method

In my example, I have an array of objects which I want to map to another array of objects:在我的示例中,我有一个对象数组,我想将其映射到另一个对象数组:

Resurs.map((item) => ({
  Cen: item.Cent,
  level: [
    item.NumList.map((item) => ({
      Kom: item.Number,
      Num: item.Kor,
    })),
    item.SerList.map((item) => ({
      Kom2: item.Ser,
    })),
  ],
}));

So, I have 2 map methods inside the map method.所以,我在 map 方法中有 2 个 map 方法。 It will return:它将返回:

{
  Cen: "aaa",
  level: [
    [ // -> want to get rid of this
      {
        Kom: "aaa",
        Num: "aaa",
      },
      {
        Kom: "bbb",
        Num: "bbb",
      },
    ], // -> and this
    [ //-> and this
      { Kom2: "aaa" },
      { Kom2: "bbb" },
    ], //-> and this
  ],
};

So, both map functions need to be inside level key, but not as a list which has two lists inside, but as a list with objects.因此,两个映射函数都需要在level键内,但不是作为内部有两个列表的列表,而是作为带有对象的列表。

So, I want to achieve:所以,我想实现:

{
  Cen: "aaa",
  level: [
    {
      Kom: "aaa",
      Num: "aaa",
    },
    {
      Kom: "bbb",
      Num: "bbb",
    },
    { Kom2: "aaa" },
    { Kom2: "bbb" },
  ],
};

You are almost there!你快到了! The answer is spread operator.答案是扩展运算符。 Just insert it in your inner map.只需将其插入您的内部地图中。

You can use a spread operator to expanded the arrays when you insert into level.插入级别时,您可以使用扩展运算符来扩展数组。

The spread operator can be used with an array or an object.扩展运算符可以与数组或对象一起使用。

Example:例子:

var a = [1, 2, 3, 4];
var b = [5, 6, 7];

var c = [a, b];   //  [[1, 2, 3, 4], [5, 6, 7]]  // This is what you are doing

Solution: 
var d = [...a, ...b];   //  [1, 2, 3, 4, 5, 6, 7]

Complete Solution:完整的解决方案:

 const Resurs = [ { Cent: "centValue", NumList: [ { Number: "numValue1", Kor: "KorValue1" }, { Number: "numValue3", Kor: "KorValue2" }, { Number: "numValue3", Kor: "KorValue3" } ], SerList: [ { Ser: "SerValue1" }, { Ser: "SerValue2" } ] } ]; const data = Resurs.map((item) => ({ Cen: item.Cent, level: [ ...item.NumList.map((item) => ({ // Just add ... Kom: item.Number, Num: item.Kor, })), ...item.SerList.map((item) => ({ // Just add ... Kom2: item.Ser, })), ], })); console.log(data);

Don't create the outer array in the first place:首先不要创建外部数组:

const data = Resurs.map((item) => ({
  Cen: item.Cent,
  level: item.NumList.map((item) => ({
      Kom: item.Number,
      Num: item.Kor,
    })).concat(item.SerList.map((item) => ({
      Kom2: item.Ser,
    }))),
}));

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

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