根据另一个数组

时间:2016-08-03 22:17:44

标签: javascript arrays

我有一个像这样的对象数组:

var bridges = {"countyCd:15
createdDate:"0001-01-01T00:00:00"
createdUserId:0
createdUserIdZ:null
createdUserName:null
description:"SR 1@.-CENTRAL 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]

如何创建另一个数组,只保留两个属性,使其变为

bridges = {" countyCd:15         nbiNumber:10"        ,[...] ....}

基本上,我正在寻找一种方法来创建一个函数,该函数将数据数组和过滤器数组作为参数,并根据过滤器数组过滤数据数组。

任何对此的指示都将非常感激。

2 个答案:

答案 0 :(得分:3)

一个解决方案是将map覆盖每个记录,将reduce过滤器数组放入包含目标属性的对象中:

var bridges = [{
    countyCd:15,
    createdDate:"0001-01-01T00:00:00",
    createdUserId:0,
    createdUserIdZ:null,
    createdUserName:null,
    description:"SR 1@.-CENTRAL 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 1@.-CENTRAL 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 :(得分: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