Skip to content
Advertisement

merge Object and array mapping object key [closed]

Merge one object into array object basis on object key and array object key mapped

{
'id':49,
'city':'bangalore',
'country':'India'
}
arr=[{
{title: 'Location ID', field: 'id', width: 200, _width: 200, filter: 'text'},
{title: 'City', field: 'city', width: 200, _width: 200, filter: 'dropdown'},
{title: 'Country', field: 'country', width: 200, _width: 200, filter: 'dropdown'}
}]

expected results:
[{
{'id':49,title: 'Location ID', field: 'id', width: 200, _width: 200, filter: 'text'},
{'city':'bangalore',title: 'City', field: 'city', width: 200, _width: 200, filter: 'dropdown'},
{'country':'India',title: 'Country', field: 'country', width: 200, _width: 200, filter: 'dropdown'}
}]```

I tried below code
console.log([...Obj,...arr])

Advertisement

Answer

You can use Array.prototype.map() combined with Destructuring assignment

Code:

const obj = { id: 49, city: 'bangalore', country: 'India' }
const arr = [{title: 'Location ID',field: 'id',width: 200,_width: 200,filter: 'text',},{ title: 'City', field: 'city', width: 200, _width: 200, filter: 'dropdown' },{title: 'Country',field: 'country',width: 200,_width: 200,filter: 'dropdown',},]

const result = arr.map(({ field, ...o }) => ({
  [field]: obj[field],
  ...o
}))

console.log(result)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement