我想获得一个对象数组,其中每个“父”对象都包含多个“子”对象,具体取决于“ idCompany”属性
这是我创建的代码,但这会产生我
我的代码
mergeProvider(){
let mergeProviders = []
for(let i = 0; i < this.companies.length; i++){
for(let j = 0; j < this.provides.length; j++){
if(this.companies[i].idCompany === this.provides[j].idCompany){
mergeProviders.push({
companyName: this.companies[i].companyName,
idCompany: this.companies[i].idCompany,
providers:{
idProvider: this.provides[j].id,
fullName: this.provides[j].label
}
})
}
}
}
},
生成此
0: {companyName: "CHCC", idCompany: 1514, provides: {…}}
1: {companyName: "CHCC", idCompany: 1514, provides: {…}}
2: {companyName: "CHCC", idCompany: 1514, provides: {…}}
3: {companyName: "CHCC", idCompany: 1514, provides: {…}}
.
.
.
n...
对于每个:
n: {companyName: "CHCC", idCompany: 1514, provides:{fullName: "name", idProvider: "1111"}
我希望输出是这个。
n: {
companyName: "CHCC",
idCompany: 1514,
provides:[
{fullName: "name", idProvider: "1111"},
{fullName: "name2", idProvider: "2222"},
{fullName: "name3", idProvider: "3333"},
{fullName: "name4", idProvider: "4444"},
{...}
]
答案 0 :(得分:0)
function mergeProvider() {
const _companies = {};
this.companies.forEach(company => {
this.providers.forEach(provider => {
if (company.idCompany === provider.idCompany) {
const { companyName, idCompany } = company;
const { fullName, idProvider } = provider;
_companies[idCompany] = _companies[idCompany] || { companyName, idCompany, providers: [] };
// check for duplicate providers
if ( !_companies[idCompany].provider.map(p => p.idP).includes(idProvider) ) {
_companies[idCompany].providers.push({fullName, idProvider})
}
}
})
});
return Object.values(_companies);
}
如果companies
和providers
都是数组,则应该起作用