我想弄清楚最好的方法來做一些對象迭代/變異。我試圖找到具有「DB」角色的服務器的所有「sids」。預期的結果將是一個變量,它具有任何具有角色DB的服務器的SID的完整道具(層,sidadm,sid,orasid,服務器)。遍歷對象數組,並過濾掉不匹配
數據
var landscape = [
{
"tier": "production",
"sidadm": "ptpadm",
"sid": "PTP",
"orasid": "oraptp",
"servers": [
{
"hostname": "testep00",
"roles": ["DB"]
},
{
"hostname": "testep01",
"roles": ["DG"]
},
{
"hostname": "testep02",
"roles": ["SAPMS"]
},
{
"hostname": "testep03",
"roles": ["SAPDI"]
},
{
"hostname": "testep04",
"roles": ["SAPDI"]
},
{
"hostname": "testep05",
"roles": ["SAPDI"]
},
{
"hostname": "testep06",
"roles": ["SAPDI"]
}
]
},
{
"tier": "techsandbox",
"sidadm": "bwzadm",
"sid": "BWZ",
"orasid": "orabwz",
"servers": [
{
"hostname": "testbw80",
"roles": ["DB"]
},
{
"hostname": "testbw81",
"roles": ["DG"]
},
{
"hostname": "testbw82",
"roles": ["SAPMS"]
},
{
"hostname": "testbw83",
"roles": ["SAPDI"]
}
]
},
{
"tier": "techsandbox",
"sidadm": "eczadm",
"sid": "ECZ",
"orasid": "oraecz",
"servers": [
{
"hostname": "testec81",
"roles": ["DG"]
},
{
"hostname": "testec82",
"roles": ["SAPDI", "SAPMS"]
}
]
}
];
這是我迄今爲止它還挺工作,但不排除具有空的服務器道具的SID。用lodash寫出這個更好的方法,對吧?
// find me all SIDs with role "DB",
// should filter landscape and only return sids which have servers role=DB
// also should only contain the servers which are role=DB
var ls = _.extend({}, landscape);
_.each(ls, function (sid) {
var servers = _.filter(sid.servers, function (server) {
return _.contains(server.roles, 'DB');
});
// still need to strip out SID objects which have empty servers prop
sid.servers = servers;
});
console.log('sids1() ::', ls);
使用'reject' https://lodash.com/docs#reject – Edmund