-1

Looking for a way to merge Javascript Object keys inside array, only on matching Ids. Should i use Map? or flatmap? I have

const districtList =[
  { id:'1234blah', companyId:'09871345', districtName:'abc1' },
  { id:'2341blah', companyId:'87134590', districtName:'abc2' },
  { id:'3412blah', companyId:'09134587', districtName:'abc3' },
]

and

const companyList =[
  {id:'09871345', companyName:'CompanyOne',   info:'some'  },
  {id:'87134590', companyName:'CompanyTwo',   info:'stuff' },
  {id:'09134587', companyName:'CompanyThree', info:'todo'  },
]

But what i want is the data from the company array inside the district array, to get the missing company name, and other info.

const improvedDistrictList =[
  { id:'1234blah', companyId:'09871345', districtName:'abc1', companyName:'CompanyOne',   info:'some'  },
  { id:'2341blah', companyId:'87134590', districtName:'abc2', companyName:'CompanyTwo',   info:'stuff' },
  { id:'3412blah', companyId:'09134587', districtName:'abc3', companyName:'CompanyThree', info:'todo'  },
]
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
DarkAdvent
  • 33
  • 7

2 Answers2

0

I would map through the district list, find a corresponding company for each one based on the companyId and then just add more fields to the new array with one caveat: it looks like your companyList array may or may not contain companyName. As such:

const districtList =[
    {id:'1234blah',companyId:'09871345', districtName:'abc1'},
    {id:'2341blah',companyId:'87134590', districtName:'abc2'},
    {id:'3412blah',companyId:'09134587', districtName:'abc3'},
]

const companyList =[
    {id:'09871345',companyName:'CompanyOne', info:'some'},
    {id:'87134590',companyId:'CompanyTwo', info:'stuff'},
    {id:'09134587',companyId:'CompanyThree', info:'todo'},
]

const result = districtList.map(item => {
    const company = companyList.find(c => c.id === item.companyId);
    return {...item, [company.companyName ? 'companyName' : 'companyId']: company.companyName ? company.companyName : company.companyId, info: company.info }
})

console.log(result)

Also, as pointed out in the comments, you won't end up with 2 companyId keys in the resulting array as the latter will override the former.

codemonkey
  • 7,325
  • 5
  • 22
  • 36
0

this way...

const districtList =[
  { id:'1234blah', companyId:'09871345', districtName:'abc1' },
  { id:'2341blah', companyId:'87134590', districtName:'abc2' },
  { id:'3412blah', companyId:'09134587', districtName:'abc3' },
]
const companyList =[
  {id:'09871345', companyName:'CompanyOne',   info:'some'  },
  {id:'87134590', companyName:'CompanyTwo',   info:'stuff' },
  {id:'09134587', companyName:'CompanyThree', info:'todo'  },
]

const improvedDistrictList = companyList.map(cl=>
  ({...cl,...districtList.find(x=>x.companyId===cl.id)}))
  
console.log( improvedDistrictList )
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40