【问题标题】:Join nested array加入嵌套数组
【发布时间】:2015-06-12 06:42:22
【问题描述】:

我有来自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

【问题讨论】:

  • 你能添加样本数组吗
  • 您的样本只是 一个 数组,但您的问题是您有一个数组(例如嵌套数组)。
  • @T.J.Crowder 是的,它是一个数组的样本。所有其他数组都遵循相同的结构
  • 如果你有一个简单的循环来做你想做的事,我会坚持下去。我敢打赌,它会比已经提出的 LoDash 解决方案更具可读性。

标签: javascript arrays lodash


【解决方案1】:

我相信这将是flattenDeep(进行展平)和without(删除nulls 的组合——至少,我认为您想删除nulls;如果没有,请采取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>"
);
&lt;script src="https://cdn.rawgit.com/lodash/lodash/3.0.1/lodash.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 我更喜欢 compact() 而不是 without() 来删除 falsey 值。
  • @AdamBoduch:我不知道他想删除所有虚假值。 :-) 实际上,我不太确定我从哪里得到他想要删除 nulls 的想法,但我很确定他确实......
  • @T.J.Crowder,是的,我实际上想删除nulls,这就是为什么我提到可能还有null 值。但是没有我明确提到你使用了without().Great
【解决方案2】:

您可以简单地使用.map 函数。

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

DEMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多