2016-08-17 61 views
-3

我有以下形式的Javascript合併

"myData": [{ 
    "items": [{ 
     "attr1": "someInfoBatch1", 
     "attr2": "someOtherInfoBatch1" 
    }], 
    "someStates": [ "STATE_PASS_1" ] 
},{ 
    "items": [{ 
     "attr1": "someInfoBatch2", 
     "attr2": "someOtherInfoBatch2" 
    }], 
    "someStates": [ "STATE_PASS_1", "STATE_FAILED_1" ] 
}] 

現在我想基於值someStates

所以合併myData.items數組的myData如果someStates包含通在一個批次&其他失敗一批(即說STATE_FAILED_1),我想myData.items是獨立的(即myData.item[0] & myData.item[1]

但是讓我們假設在上面的例子中someStates只包含如下的傳遞狀態;對於第一批"someStates":["STATE_PASS_1"] &爲第二批"someStates":["STATE_PASS_1", "STATE_PASS_2"]

在上述情況下,我需要myData.items合併成如下面的單個陣列;

"items": [{ 
    "attr1": "someInfoBatch1", 
    "attr2": "someOtherInfoBatch1" 
},{ 
    "attr1": "someInfoBatch2", 
    "attr2": "someOtherInfoBatch2" 
}] 
+2

不知道這兩行究竟是如何在你的例子不同。爲了遵循你的描述:一般來說,只需編寫你自己的myData映射器,用'.some((statePassFlag)=> {/^STATE_FAILED/.test(statePassFlag)})檢查每個後續對象'someStates'值' – raina77ow

+0

但是可以合併2個數組嗎? – testndtv

+0

當然:'[] .push.apply(onearr,anotherarr)''。但是你在這裏展示的不是_merge_本身。 – raina77ow

回答

0

分解undescore.js:

// Return the results of applying the iteratee to each element. 
    var map = function(obj, iteratee, context) { 
    iteratee = cb(iteratee, context); 
    var keys = !isArrayLike(obj) && _.keys(obj), 
     length = (keys || obj).length, 
     results = Array(length); 
    for (var index = 0; index < length; index++) { 
     var currentKey = keys ? keys[index] : index; 
     results[index] = iteratee(obj[currentKey], currentKey, obj); 
    } 
    return results; 
    }; 

    var property = function(key) { 
    return function(obj) { 
     return obj == null ? void 0 : obj[key]; 
    }; 
    }; 

和呼叫:var items = map(myData, property("items"));

0

你可以只需使用Array#map爲它。

var $scope = { "myData": [{ "items": [{ "attr1": "someInfoBatch1", "attr2": "someOtherInfoBatch1" }], "someStates": ["STATE_PASS_1"] }, { "items": [{ "attr1": "someInfoBatch2", "attr2": "someOtherInfoBatch2" }], "someStates": ["STATE_PASS_1", "STATE_FAILED_1"] }] }, 
 
    items = $scope.myData.map(function (a) { 
 
     return a.items[0]; 
 
    }); 
 

 
console.log(items);

ES6

var $scope = { "myData": [{ "items": [{ "attr1": "someInfoBatch1", "attr2": "someOtherInfoBatch1" }], "someStates": ["STATE_PASS_1"] }, { "items": [{ "attr1": "someInfoBatch2", "attr2": "someOtherInfoBatch2" }], "someStates": ["STATE_PASS_1", "STATE_FAILED_1"] }] }, 
 
    items = $scope.myData.map(a => a.items[0]); 
 

 
console.log(items);