javascript - 需要连接数组(不知道需要多少)(js)

标签 javascript arrays

我的arr 的示例 View 。

enter image description here

需要连接最深的对象,

例如有2个数组[{id1:color:grey}] [{id4:color:grey},{id8:color:grey}]

结果需要是这样的:[{id1:color:grey},{id4:color:grey},{id8:color:grey}]

尝试做一些事情,但不知道如何连接,我不知道数组可以有多少

var kkk = [];

        for (var i=0; i < arrData.length;i++) {
          var his = arrData[i][1];
          for(var k=0; k < his.length; k++) {
            console.log(his[0])
          }

        }

我必须在循环中做什么?循环是否正确?

我的目标:

Array[2]
0:"th"
1:Array[2]
   0:Array[1] //this need concat
   1:Array[1] //this need concat

["th"
,[[[{"id":4,"color":"grey"},
{"id":5,"color":"grey"},
{"id":6,"color":"grey"},
{"id":7,"color":"grey"},
{"id":8,"color":"grey"},
{"id":9,"color":"grey"},
{"id":10,"color":"grey"},
{"id":11,"color":"grey"},{"id":12,"color":"grey"}]],

[[{"id":19,"color":"grey"},{"id":20,"color":"grey"},{"id":21,"color":"grey"}

]]]]

最佳答案

您可以展平数组,然后将结果连接到数组中。

我使用了 one 中的代码我的仓库。

var arr = [[[{color : "red", id : 1}]],[{color : "green", id : 2}],[[[{color : "yellow", id : 3}]]],[{color : "blue", id : 4}]];

const __flattenReducer = (result,value,valueIndex,arr)=>{
  if(value instanceof Array){
    return value.reduce(__flattenReducer,result);
  }else{
    result.push(value);
    return result;
  }
};

const flatten = function(arr){
   if(arr instanceof Array){
     return Array.prototype.reduce.apply(arr,[__flattenReducer,[]]);
   }else{
     throw new TypeError('Expected an array');
   }
}

console.log(flatten(arr))

关于javascript - 需要连接数组(不知道需要多少)(js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45853900/

相关文章:

javascript - 在 mongoose express 中选择几个字段作为数组

java - 交换数组中对应的元素

javascript - 如何访问嵌套的 json 数组以获取每个对象中所有参数的所有值的列表

javascript - 从智能手机和平板电脑识别用户并隐藏元素

javascript - Google 表格的查找/颜色脚本,访问外部循环变量不起作用

javascript - Angular 模式和 ng 模型错误

python - 切片 3d numpy 数组返回奇怪的形状

javascript - 如何在用户按下刷新按钮时限制随机播放

javascript - 在 Canvas 上移动对象

javascript - 当字符串包含 unicode 字符时,不能总是成功使用 String.startsWith()