Home > Software engineering >  JS - Merge Objects
JS - Merge Objects

Time:11-23

I need to merge/combine 4 objects inside and array. The objects are:

{"field": "name","lang": "it","text": "RegoleAziendali"}
{"field": "pdf_url","lang": "it", "text": "docs/it/file.pdf"}
{"field": "name","lang": "en","text": "CompanyRules"}
{"field": "pdf_url","lang": "en", "text": "docs/en/file.pdf"}

Expected Result Should Be made of 2 objects merged by the language.

{"lang": "it","name": "RegoleAziendali","pdf_url":"docs/it/file.pdf"}
{"lang": "en","name": "CompanyRules","pdf_url":"docs/en/file.pdf"}

At the moment I am using array.forEach to merge two objects by lang. But I can not find a way to manipulate the values/properties. As you can see the property "field" is no longer needed in the merged objects.

CodePudding user response:

assuming you have an array, you can convert this to a grouping problem.

Group by lang using reduce.
After that take the values array of the grouped object using Object.values

const x = [
{"field": "name","lang": "it","text": "RegoleAziendali"},
{"field": "pdf_url","lang": "it", "text": "docs/it/file.pdf"},
{"field": "name","lang": "en","text": "CompanyRules"},
{"field": "pdf_url","lang": "en", "text": "docs/en/file.pdf"}
]

const res = Object.values(x.reduce((acc,{field,lang,text}) => {
  acc[lang] = acc[lang] || {lang}
  acc[lang][field] = text
  return acc
},{}))

console.log(res)

the same thing can be done using a for loop

const x = [{"field": "name","lang": "it","text": "RegoleAziendali"},{"field": "pdf_url","lang": "it", "text": "docs/it/file.pdf"},{"field": "name","lang": "en","text": "CompanyRules"},{"field": "pdf_url","lang": "en", "text": "docs/en/file.pdf"}]

const res = {}
for (const entry of x){
  const {field,lang,text} = entry
  res[lang] = res[lang] || {lang}
  res[lang][field] = text
}

console.log(Object.values(res))

CodePudding user response:

const arr = [{"field": "name","lang": "it","text": "RegoleAziendali"}, {"field": "pdf_url","lang": "it", "text": "docs/it/file.pdf"}, {"field": "name","lang": "en","text": "CompanyRules"}, {"field": "pdf_url","lang": "en", "text": "docs/en/file.pdf"}];


const ans = arr.reduce((a,{field,lang,text}) => ({...a, [lang]: {...a[lang], [field]: text, lang }}), {});

console.log(Object.values(ans));

CodePudding user response:

To cherry-pick certain fields:

const data = [
  {"field": "name","lang": "it","text": "RegoleAziendali"},
  {"field": "pdf_url","lang": "it", "text": "docs/it/file.pdf"},
  {"field": "name","lang": "en","text": "CompanyRules"},
  {"field": "pdf_url","lang": "en", "text": "docs/en/file.pdf"}
]

const lookup = (lang, field) => ({
  [field]: data.find(i=>i.lang===lang && i.field===field).text
})

console.log([...new Set(data.map(i=>i.lang))].map(lang=>({
  lang, ...lookup(lang, 'name'), ...lookup(lang, 'pdf_url')
})))

  • Related