【问题标题】:Merger chunks of array objects to single array将数组对象块合并到单个数组
【发布时间】:2018-05-31 06:37:15
【问题描述】:

我必须在 Angularjs 中将数组块合并为单个数组和对象数组。

我的输入数组会是这样的:

[
  [
    {
      "title": "asd",
      "description": "asd"
    },
    {
      "title": "asz",
      "description": "sd"
    }
  ],
  [
    {
      "title": "ws",
      "description": "sd"
    },
    {
      "title": "re",
      "description": "sd"
    }
  ],
  [
    {
      "title": "32",
      "description": "xxs"
    },
    {
      "title": "xxc",
      "description": "11"
    }
  ]
]

上面的输入数组应该像下面的对象数组一样保存

[
  {
    "title": "asd",
    "description": "asd"
  },
  {
    "title": "asz",
    "description": "sd"
  },
  {
    "title": "ws",
    "description": "sd"
  },
  {
    "title": "re",
    "description": "sd"
  },
  {
    "title": "32",
    "description": "xxs"
  },
  {
    "title": "xxc",
    "description": "11"
  }
]

请建议我如何实现这一目标。

提前非常感谢

【问题讨论】:

  • 数组的数量是固定的吗?
  • 不..可能会有所不同

标签: javascript arrays angularjs


【解决方案1】:

您可以使用.reduce().concat()

let data = [[{"title": "asd","description": "asd"},{"title": "asz","description": "sd"}],[{"title": "ws","description": "sd"},{"title": "re","description": "sd"}],[{"title": "32","description": "xxs"},{"title": "xxc","description": "11"}]];

let result = data.reduce((a, c) => a.concat(c), []);

console.log(result);

【讨论】:

    【解决方案2】:

    您可以使用 concat() 和扩展运算符 (...):

    var arr = [
      [
        {
          "title": "asd",
          "description": "asd"
        },
        {
          "title": "asz",
          "description": "sd"
        }
      ],
      [
        {
          "title": "ws",
          "description": "sd"
        },
        {
          "title": "re",
          "description": "sd"
        }
      ],
      [
        {
          "title": "32",
          "description": "xxs"
        },
        {
          "title": "xxc",
          "description": "11"
        }
      ]
    ]
    
    var res = [].concat(...arr);
    console.log(res);

    【讨论】:

      【解决方案3】:

      您只是在寻找一种平面地图的方法,使用concat 和传播很容易:

      const input=[[{"title":"asd","description":"asd"},{"title":"asz","description":"sd"}],[{"title":"ws","description":"sd"},{"title":"re","description":"sd"}],[{"title":"32","description":"xxs"},{"title":"xxc","description":"11"}]]
      const output = [].concat(...input);
      console.log(output);

      【讨论】:

        猜你喜欢
        • 2015-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-22
        • 2020-06-28
        • 1970-01-01
        • 2022-11-08
        • 1970-01-01
        相关资源
        最近更新 更多