如何与其他对象合并

时间:2019-06-18 22:11:58

标签: javascript arrays object vue.js

我想获得一个对象数组,其中每个“父”对象都包含多个“子”对象,具体取决于“ 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"},
  {...}
]

1 个答案:

答案 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);
}

如果companiesproviders都是数组,则应该起作用