'concatenate several objects with the same name and index
listAnimal.json
[
0:
{
base: {address: 'address house 1', animal: 'DOG', name: 'boby'}
},
1:
{
base: {address: 'address house 2', animal: 'CAT', name: 'pippo'}
},
2:
{base: {address: 'address house 3', animal: 'TIGER', name: 'best'}
},
3:
{base: {address: 'address house 4', animal: 'HORSE', name: 'lino'}
},
]
otherInformation.json
[{
"boby":
{ "id":1,
"img":"link img dog",
"forum":" link forum dog"
},
"pippo":
{ "id":2,
"img":"link img cat",
"forum":" link forum cat"
},
"best":
{ "id":3,
"img":" link img tiger",
"forum":" link forum tiger"
}, ]
good morning everyone, i have these 2 json files which i can't concatenate as i want let me explain better, the final result should be that is, you have to join who has the same name and index
[
0:
{
base: {address: 'address house 1', animal: 'DOG', name: 'boby'}
"id":1,
"img":"link img dog",
"forum":" link forum dog"
},
etc
I have tried with several methods "Object.assign ()", "Object.concat () I add the objects in the array but as new indexes
Solution 1:[1]
you can do this
const info = [
{
"boby":
{
"id": 1,
"img": "link img dog",
"forum": " link forum dog"
}
},
{
"pippo":
{
"id": 2,
"img": "link img cat",
"forum": " link forum cat"
}
},
{
"best":
{
"id": 3,
"img": " link img tiger",
"forum": " link forum tiger"
}
},
]
const infoObj = Object.assign({}, ...info)
const animals = [
{
base: {
address: 'address house 1',
animal: 'DOG',
name: 'boby'
}
},
{
base: {
address: 'address house 2',
animal: 'CAT',
name: 'pippo'
}
},
{
base: {
address: 'address house 3',
animal: 'TIGER',
name: 'best'
}
},
{
base: {
address: 'address house 4',
animal: 'HORSE',
name: 'lino'
}
},
]
const result = animals.map(a => ({
...a,
...(infoObj[a.base.name] || {})
}))
console.log(result)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R4ncid |
