0

I have a dynamic array which is like this.

    var callData = [
        {
            "FIELD_1": "0763454333"
        },
        {
            "FIELD_2": "dgfdgfg"
        },
        {
            "FIELD_3": "fgfdgfdg"
        }
    ];

According to the user, these number of fields changes. If another user has more fields, there can be FIELD_4, FIELD_5 and so on. I fetch these data from db and put it into and array as above. Now I want to convert it a single object. I want it to look like this.

    {
        "FIELD_1": "076355998", "FIELD_2": "933504395v", "FIELD_3": "123"
    }

Although I found converting solutions in stackoverflow, Those didn't solve my problem. How can I achieve this? Please guide.

JakeParis
  • 11,056
  • 3
  • 42
  • 65
Buwaneka Sudheera
  • 1,277
  • 4
  • 17
  • 35

1 Answers1

3

use flatMap function to return entries of each object and then use Object.fromEntries function to create an object from the entries

var callData = [
  {"FIELD_1": "0763454333" },
  { "FIELD_2": "dgfdgfg" },
  { "FIELD_3": "fgfdgfdg" }
];

const res = Object.fromEntries(callData.flatMap(o => Object.entries(o)));

console.log(res);
Yousaf
  • 27,861
  • 6
  • 44
  • 69