加入嵌套数组

时间:2015-06-12 06:42:22

标签: javascript arrays lodash

我有Q.all()的结果,就像这样 -

promise = [Arr1,Arr2,Arr3....]

每个Arr可以是null,也可以是普通JS对象的数组。

我想将所有这些数组连接到一个大数组;

我可以循环并使用数组concat方法加入它们。

是否有其他优雅的解决方案在JS中内置?

这是示例数组 -

    [
      {
        "endDate": "2015-06-11 14:52:00",
        "quantity": 75,
      },
      {
        "endDate": "2015-06-11 14:42:00",
        "quantity": 78,
      },
      {
        "endDate": "2015-06-01 14:43:00",
        "quantity": 69,
      },
      {
        "endDate": "2015-05-14 13:38:00",
        "quantity": 85,
      }
    ]
  

我也可以使用这些库lodashangular

2 个答案:

答案 0 :(得分:3)

我认为这将是flattenDeep(做扁平化)和without(去除null s的组合 - 至少,我认为你想删除{{1如果没有,请取出null

without

直播示例:

var result = _.without(_.flattenDeep(yourArray), null);
// NOTE: You said you had an array with arrays in it, so I've taken
// the one array you gave and used it as two entries in the array
// below (with some minor mods). Note also the nulls.
var yourArrays = [
    [
        {
            "endDate": "2015-06-11 14:52:00",
            "quantity": 75
        },
        {
            "endDate": "2015-06-11 14:42:00",
            "quantity": 78
        },
        {
            "endDate": "2015-06-01 14:43:00",
            "quantity": 69
        },
        {
            "endDate": "2015-05-14 13:38:00",
            "quantity": 85
        }
    ],
    null,
    null,
    [
        {
            "endDate": "2015-07-11 14:52:00",
            "quantity": 12
        },
        {
            "endDate": "2015-07-11 17:42:00",
            "quantity": 34
        },
        {
            "endDate": "2015-07-01 13:43:00",
            "quantity": 56
        },
        {
            "endDate": "2015-08-14 12:38:00",
            "quantity": 85
        }
    ]
];
var result = _.without(_.flattenDeep(yourArrays), null);
document.body.insertAdjacentHTML(
"beforeend",
"<pre>" + JSON.stringify(result, null, 2) + "</pre>"
);

答案 1 :(得分:0)

你可以简单地使用.map功能。

var promise = [[0,1],[2,3],[],[6,7]]
var combineArr = promise.map(function(value, index, array) {
    return array[index];
  });
alert(combineArr);  

DEMO

相关问题