我有两个javascript数组一个
var sectors = [
{ name: 'Fishing' }, {name: 'Bowling'}...
];
另一个
var organizations = [
{name: 'Carson ind', tel: '1545454', fax: 1215454, sectors: ['Banking', 'Fishing']},
{name: 'Superman & Co.', tel: '1545454', fax: 1215454, sectors: ['Financing', 'Banking']},
....
];
如何用这个具有以下结构的两个数组创建新数组。
var newArray = [
{sector : 'Banking', organizations :
[
{name: 'Superman & Co.', tel: '1545454', fax: 1215454, sectors: ['Financing', 'Banking']},
....
]
}
];
现在我使用下划线和我的代码
var newArray = [];
_.each(vm.allSectors, function(sec){
newArray[sec.name] = _.filter(vm.allOrganizations, function(org) {
return _.filter(org.sector, function(sector){
return sector === sec.name;
});
});
});
它没有给我结果我希望它只返回很多扇区数组。
答案 0 :(得分:1)
基本上是user6188402的答案,但是有固定的lambdas
result = sectors.map(s => {
return {
sector: s.name,
organizations: organizations.filter(o => o.sectors.indexOf(s.name) > -1)
}
});
答案 1 :(得分:0)
此提案使用所需扇区的对象并迭代organisations
并创建新对象并将实际数据插入组织属性。
var sectors = [{ name: 'Fishing' }, { name: 'Bowling' }],
sectorHash = {},
organizations = [{ name: 'Carson ind', tel: '1545454', fax: 1215454, sectors: ['Banking', 'Fishing'] }, { name: 'Superman & Co.', tel: '1545454', fax: 1215454, sectors: ['Financing', 'Banking'] }],
newArray = [];
sectors.forEach(function (a) {
sectorHash[a.name] = true;
});
organizations.forEach(function (a) {
a.sectors.forEach(function (b) {
if (sectorHash[b]) {
if (!this[b]) {
this[b] = { sector: b, organzations: [] };
newArray.push(this[b]);
}
this[b].organzations.push(a);
}
}, this);
}, Object.create(null));
document.write('<pre>' + JSON.stringify(newArray, 0, 4) + '</pre>');