gpt4 book ai didi

javascript - 加入嵌套数组

转载 作者:行者123 更新时间:2023-11-29 10:40:06 27 4
gpt4 key购买 nike

我有一个来自 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,
}
]

I have these libraries available as well lodash, angular

最佳答案

我相信这将是 flattenDeep 的组合(做展平)和without (删除 null — 至少,我认为您想要删除 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>"
);
<script src="https://cdn.rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>

关于javascript - 加入嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30796817/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com