I have an array as input which contains some JSONs.
The JSONs have the same field 'address' field, how can I get all the "street", "name", "type" in a Json array?
Input
[
{
"address": {
"street" : "aaaa",
"name": "dsd",
"type": "sds"
}
},
{
"address": {
"street" : "bbbb",
"name": "gdg",
"type": "gdg"
}
},
...
]
Output
{"address": [
{
"street" : "aaaa",
"name": "dsd",
"type": "sds"
},
{
"street" : "bbbb",
"name": "gdg",
"type": "gdg"
},
...
]
}
CodePudding user response:
You can use reduce
to accumulate the array to an object with an address
key equal to the array and push the items inside.
const data = [
{
"address": {
"street" : "aaaa",
"name": "dsd",
"type": "sds"
}
},
{
"address": {
"street" : "bbbb",
"name": "gdg",
"type": "gdg"
}
},
]
const result = data.reduce((acc, item) => {
acc.address.push(item)
return acc;
}, {
address: []
})
console.log(result)
Or you can use forEach
loop
const data = [
{
"address": {
"street" : "aaaa",
"name": "dsd",
"type": "sds"
}
},
{
"address": {
"street" : "bbbb",
"name": "gdg",
"type": "gdg"
}
},
]
let result = { address: []}
data.forEach(item => {
result.address.push(item);
})
console.log(result)
CodePudding user response:
const address = data.reduce((acc, addr) => {
return {
address: acc.address.concat(addr)
};
}, { address: [] });