1

I have an array of json -

var finalResponse2 = [
{Transaction Amount: {type: "number"}},
{UTR number: {type: "string"}}
]

And I want to convert it like this

responses : [
{
Transaction Amount: {type: "number"},
UTR number: {type: "string"}
}]

I have written the code like -

     var innerField1 =  {};
      var innerField2 = {};
      for (var l=0 ; l < this.finalResponse2.length ; l++){

        let key1 = Object.keys(this.finalResponse2[l])[0]
       let value1 = Object.values(this.finalResponse2[l])[0]
       let key2  = Object.keys(value1)[0]
       let value2 =  Object.values(value1)[0]


       innerField1[key2] = value2 
       key1[key2] = value2

       key1.key2 = value2
        fields['responses'].key1.key1[key2] = value2
      }

    }

But I am getting error - Cannot create property 'type' on string 'Transaction Amount'

Techdive
  • 997
  • 3
  • 24
  • 49
  • 1
    First, that is not JSON and second, I doubt that you really have defined the object in your example that way since it is invalid. Third: https://stackoverflow.com/questions/27538349/merge-multiple-objects-inside-the-same-array-into-one-object – Lain Nov 01 '19 at 14:17

1 Answers1

4

You can use Object.assign function and spread operator ... to get the desired result:

let finalResponse2 = [
 {"Transaction Amount": {type: "number"}},
 {"UTR number": {type: "string"}}
];

let result = [Object.assign({}, ...finalResponse2)];
console.log(result);
StepUp
  • 36,391
  • 15
  • 88
  • 148