rubyist
rubyist

Reputation: 3132

merge json arrays and generate key value pair

I am reading 3 json files in backend from S3 bucket and getting the data in below format.

readJSON  = async (params) => { 

    const data = (await (S3.getObject(params).promise())).Body.toString('utf-8'); 

    return JSON.parse(data); 

}

params wiill have bucket name and keys (filenames)

Output json data is coming as

[
   {
      "awsregion":"ap-southeast-2"
   },
   {
      "awsregion":"us-west-1"
   },
   {
      "awsregion":"eu-north-1"
   },
   {
      "awsregion":"ap-northeast-1"
   },
   {
      "awsregion":"ap-south-1"
   }
][
   {
      "accountID":22180670435
   },
   {
      "accountID":681582023110
   },
   {
      "accountID":389803793257
   },
   {
      "accountID":88588205515
   },
   {
      "accountID":413557442353
   }
]

I want to merge it as a single json object. The idea is to access these json objects with related keys in front endand do some formatting. So I am thinking to merge it in single json object in the following format.

var data = 
{
   "awsregion":[
      {
         "awsregion":"ap-southeast-2"
      },
      {
         "awsregion":"us-west-1"
      },
      {
         "awsregion":"eu-north-1"
      },
      {
         "awsregion":"ap-northeast-1"
      },
      {
         "awsregion":"ap-south-1"
      }
   ],
   "accountID":[
      {
         "accountID":22180670435
      },
      {
         "accountID":681582023110
      },
      {
         "accountID":389803793257
      },
      {
         "accountID":88588205515
      },
      {
         "accountID":413557442353
      }
   ]
}

Now I will be able to access it as data.awsregion and data.accountID which will return as arrays. How can this be possible in javascript/nodejs

Upvotes: 0

Views: 513

Answers (1)

EugenSunic
EugenSunic

Reputation: 13703

First flatten your arrays to have objects in one array and use reduce on it.

Group by the object key. Check if the key exists, if yes add the object to the existing array if not instantiate the array for that Object property and add the first item to it.

Note

since you have multiple arrays you need an array to wrap the other arrays to make your output json valid.

const list = [
  [{
      "awsregion": "ap-southeast-2"
    },
    {
      "awsregion": "us-west-1"
    },
    {
      "awsregion": "eu-north-1"
    },
    {
      "awsregion": "ap-northeast-1"
    },
    {
      "awsregion": "ap-south-1"
    }
  ],
  [{
      "accountID": 22180670435
    },
    {
      "accountID": 681582023110
    },
    {
      "accountID": 389803793257
    },
    {
      "accountID": 88588205515
    },
    {
      "accountID": 413557442353
    }
  ]
]

const result = list.flat().reduce((acc, x) => {
  const key = Object.keys(x)[0];
  if (acc[key]) {
    acc[key] = [...acc[key], x];
  } else {
    acc[key] = [x]
  }
  return acc;

}, {})

console.log(result)

Upvotes: 1

Related Questions