2016-08-03 142 views
0

我有對象的一個​​這樣的數組:篩選器屬性

var bridges = {"countyCd:15 
createdDate:"0001-01-01T00:00:00" 
createdUserId:0 
createdUserIdZ:null 
createdUserName:null 
description:"SR [email protected] RR COMP OF IND" 
districtId:null 
encryptedId1:null 
encryptedId2:null 
isDirty:false 
modelState:null 
nbiNumber:10 
routeNbr:"1" 
routeTypeCd:"SR" 
transactionType:null 
updatedDate:"0001-01-01T00:00:00" 
updatedUserId:0 
updatedUserIdZ:null 
updatedUserName:null", [...]....} 

我有這樣

[countyCd, nbiNumber] 

另一個數組如何創建另一個數組僅保留兩個屬性所以它變得像

橋= { 「countyCd:15 nbiNumber:10」 ,[...] ....}

基本上,我正在尋找一種方法來創建一個函數,該函數將數據數組和過濾器數組作爲參數,並根據過濾器數組過濾數據數組。

任何指針,將不勝感激。

+0

'bridges'實際上是一個數組,還是它像你發佈的對象?該解決方案會因此而有所不同 –

+0

@ RobM.Bridges是一個對象數組。我很抱歉我的問題含糊不清。 – w2olves

回答

3

一個解決辦法是map在每個記錄和reduce您的濾波器陣列成一個對象包含目標根據企業的性質:

var bridges = [{ 
    countyCd:15, 
    createdDate:"0001-01-01T00:00:00", 
    createdUserId:0, 
    createdUserIdZ:null, 
    createdUserName:null, 
    description:"SR [email protected] RR COMP OF IND", 
    districtId:null, 
    encryptedId1:null, 
    encryptedId2:null, 
    isDirty:false, 
    modelState:null, 
    nbiNumber:10, 
    routeNbr:"1", 
    routeTypeCd:"SR", 
    transactionType:null, 
    updatedDate:"0001-01-01T00:00:00", 
    updatedUserId:0, 
    updatedUserIdZ:null, 
    updatedUserName:null 
}, { 
    countyCd:23, 
    createdDate:"0001-01-01T00:00:00", 
    createdUserId:0, 
    createdUserIdZ:null, 
    createdUserName:null, 
    description:"SR [email protected] RR COMP OF IND", 
    districtId:null, 
    encryptedId1:null, 
    encryptedId2:null, 
    isDirty:false, 
    modelState:null, 
    nbiNumber:10, 
    routeNbr:"1", 
    routeTypeCd:"SR", 
    transactionType:null, 
    updatedDate:"0001-01-01T00:00:00", 
    updatedUserId:0, 
    updatedUserIdZ:null, 
    updatedUserName:null 
}]; 

var filters = ['countyCd', 'nbiNumber']; 
var transformedRecords = bridges.map(bridge => filters.reduce((p, c) => { 
    p[c] = bridge[c]; 
    return p; 
}, {})); 
console.log(transformedRecords); 
1

說當你有bridges的陣列,稱之爲bA

var bA = []; //bridges array 
var nbiA = []; // nbia array with countyCd 
var newA = []; // new array 
bA.forEach(function(element, index, array){ 
    var newEntry = { 
     'countyCd':element.countyCd, 
     'nbiNumber':nbiA.find(function(nbi){ 
      return nbi[countyCd] == element.countyCd; 
     }).nbiNumber 
    }; 
    newA.push(newEntry); 
}); 
//do whatever you want with the newA array