-2

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


}
3
  • 1
    Firstly, this is not JSON; JSON is a string. It's an object and this may help Working with Objects: Commented Sep 15, 2022 at 16:51
  • 1
    Secondly, what have you tried? Have you tried looking for a similar question in stack overflow? stackoverflow.com/a/6237554/1046690 Commented Sep 15, 2022 at 17:00
  • 1
    I downvoted, because the question doesn't show any attempt or research effort Commented Sep 16, 2022 at 1:33

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

0
const address = data.reduce((acc, addr) => {
  return {
    address: acc.address.concat(addr)
  };
}, { address: [] });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.