2016-04-27 39 views
0

分組,我有以下格式的2個JavaScript數組對象:我期待它以下列方式格式化在數組對象

var input1 = 
    { 
     "a" : [ 
     { 
     "id" : 1, 
     "name" : "gh" 
     }], 
     "b" : [ 
     { 
     "id" : 2, 
     "name" : "ab" 
     }] 

    } 

var input2 = 
{ 
"a" : [ 
     { 
     "id" : 3, 
     "name" : "cd" 
     }], 
     "b" : [ 
     { 
     "id" : 4, 
     "name" : "gh" 
     }] 
} 

:我想組

var finaloutput = 
    { 
     "a" : [ 
     { 
     "id" : 1, 
     "name" : "gh" 
     }, 
     { 
     "id" : 3, 
     "name" : "cd" 
     } 
     ], 
     "b" : [ 
     { 
     "id" : 2, 
     "name" : "ab" 
     }, 
     { 
     "id" : 4, 
     "name" : "gh" 
     } 
     ]  
    } 

數組而不使用任何外部庫。對javascript中的linq不熟悉,任何可用的內置函數或任何引用?

編輯:我做了在輸入的變化,因爲這是我所期待的輸入

+2

你的第一個塊不抱你怎麼想這樣做,第一個'」一個「',''b」'屬性將被第二組覆蓋。所以它將會是你的對象重新初始化密鑰的{{a:[{id:3}],b:[{id:4}]}' –

+0

。 –

回答

2

試試這個,當然這只是一個快速的FPGA實現 - 但它應該設置你正確的道路上:

var finaloutput = Object.keys(input1).reduce((p,v) => { 
    p[v] = (input1[v].concat(input2[v])) 
    return p; 
}, {}) 

回報=>

JSON.stringify(finaloutput,空,2);

"{ 
    "a": [ 
    { 
     "id": 1, 
     "name": "gh" 
    }, 
    { 
     "id": 3, 
     "name": "cd" 
    } 
    ], 
    "b": [ 
    { 
     "id": 2, 
     "name": "ab" 
    }, 
    { 
     "id": 4, 
     "name": "gh" 
    } 
    ] 
}" 
1

創建地圖並填寫檢查關鍵的存在,與任何給定數量的輸入

var allInputs = []; 
allInputs.push(input1); 
allInputs.push(input2); 

var result = []; 

for(var x in allInputs) 
{ 
    var inp = allInputs[x]; 
    for(var i in inp) 
    { 
     if(result[i] == undefined) 
     { 
      result[i] = []; 
     } 

     result[i].push(inp[i]); 
    } 
} 
0
var finalOutput; 
    var input1 = { 
      "a": [{ 
        "id": 1, 
        "name": "gh" 
      }], 
      "b": [{ 
        "id": 2, 
        "name": "ab" 
      }] 
    }; 

    var input2 = { 
      "a": [{ 
        "id": 3, 
        "name": "cd" 
      }], 
      "b": [{ 
        "id": 4, 
        "name": "gh" 
      }] 
    }; 
    input1.a.push(input2.a[0]); 
    input1.b.push(input2.b[0]); 
    finalOutput = input1; 

    //////////////////////////////////////////////////////  
    If the arrays are dynamic you can do the operation as follows: 

    var input1 = { 
     "a": [ 
      { 
       "id": 1, 
       "name": "gh" 
      } 
     ], 
     "b": [ 
      { 
       "id": 2, 
       "name": "ab" 
      } 
     ] 
} 

var input2 = { 
     "a": [ 
      { 
       "id": 3, 
       "name": "cd" 
      } 
     ], 
     "b": [ 
      { 
       "id": 4, 
       "name": "gh" 
      } 
     ] 
} 
var inputNewLengthA = input1.a.length; 
var inputNewLengthB = input1.b.length; 
var finalOutput; 
for(var v=0;v<inputNewLengthA;v++){ 
    input1.a.push(input2.a[v]); 
} 
for(var n=0;n<inputNewLengthB;n++){ 
    input1.b.push(input2.b[n]); 
} 
finalOutput = input1; 
/////////////////////////////////////// 
Note: You can also use one for loop only if your array lengths are 
equal.