-3

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"
     },
   ...
  ]


}
  • 1
    Firstly, this is not JSON; JSON is a string. It's an object and this may help [Working with Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects): – mykaf Sep 15 '22 at 16:51
  • 1
    Secondly, what have you tried? Have you tried looking for a similar question in stack overflow? https://stackoverflow.com/a/6237554/1046690 – AGE Sep 15 '22 at 17:00
  • 1
    I downvoted, because the question doesn't show any [attempt](https://idownvotedbecau.se/noattempt/) or [research effort](https://idownvotedbecau.se/noresearch/) – jabaa Sep 16 '22 at 01:33

2 Answers2

2

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)
Mina
  • 14,386
  • 3
  • 13
  • 26
0
const address = data.reduce((acc, addr) => {
  return {
    address: acc.address.concat(addr)
  };
}, { address: [] });
Kevin Aung
  • 803
  • 6
  • 12