Merge one object into array object basis on object key and array object key mapped
JavaScript
x
21
21
1
{
2
'id':49,
3
'city':'bangalore',
4
'country':'India'
5
}
6
arr=[{
7
{title: 'Location ID', field: 'id', width: 200, _width: 200, filter: 'text'},
8
{title: 'City', field: 'city', width: 200, _width: 200, filter: 'dropdown'},
9
{title: 'Country', field: 'country', width: 200, _width: 200, filter: 'dropdown'}
10
}]
11
12
expected results:
13
[{
14
{'id':49,title: 'Location ID', field: 'id', width: 200, _width: 200, filter: 'text'},
15
{'city':'bangalore',title: 'City', field: 'city', width: 200, _width: 200, filter: 'dropdown'},
16
{'country':'India',title: 'Country', field: 'country', width: 200, _width: 200, filter: 'dropdown'}
17
}]```
18
19
I tried below code
20
console.log([...Obj,...arr])
21
Advertisement
Answer
You can use Array.prototype.map() combined with Destructuring assignment
Code:
JavaScript
1
9
1
const obj = { id: 49, city: 'bangalore', country: 'India' }
2
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',},]
3
4
const result = arr.map(({ field, o }) => ({
5
[field]: obj[field],
6
o
7
}))
8
9
console.log(result)