2017-08-24 28 views
0

我的arr的示例視圖。需要連接陣列(不知道會有多少)(js)

enter image description here

有需要Concat的最深的對象,

例如有2列[{id1:color:grey}] [{id4:color:grey},{id8:color:grey}]

的結果需要是這樣的:[{id1:color:grey},{id4:color:grey},{id8:color:grey}]

嘗試做一些這一點,但不知道如何concat,我不知道有多少陣列可以

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"} 

]]]] 
+2

請分享你的對象 –

+0

你沒有什麼像'[{id1:color:gray}] [{id4:color:gray},{id8:color:gray}]''因爲那根本無效 - 有人說「分享你的對象」,並不意味着它的圖片:p –

+0

*需要連接數組*,你應該看看'Array.concat'。 – Rajesh

回答

1

您可以拼合的數組,然後拼接結果存入數組。

我使用了我回購的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))

+0

重複推送到數組將比Array.prototype.concat性能低得多 –

0
function flatten(arr) { 
    if (Array.isArray(arr)) return 
Array.prototype.concat.apply([], arr.map(flatten)); 
    return arr; 
} 

這是爲壓平的基本遞歸溶液。

相關問題