Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript convert an array to JSON

I have a complicated data structure that I need to convert to JSON. The problem is that my field names and values are in an array.

For instance, I have the following (simplified from my code base):

let SampleData = [
        { Field: 'Key', Value: '7'},
        { Field: 'City', Value: 'Some City'},
        { Field: 'Description', Value: 'Some Description'}
];

Basically my data is an array where the first element is the database column name, and the second element is the data in the column. I am trying to get a JSON object that is:

{ Key: 7, City: 'Some City', Description: 'Some Description' }

My real code has the fields and data is structures within the object, so I cannot simply use an Object.create() or Object.assign() as far as I can get working.

I have tried looping through to build a simple string and then use the JSON.parse to break it apart, but this seems like a lot of overhead for something I would have thought would be simpler.

like image 606
Steven Scott Avatar asked Jan 04 '18 18:01

Steven Scott


3 Answers

As you asked, here's how to do it:

  1. Mapping the array to an object
  2. Converting the object to JSON

let array = [{
    Field: 'Key',
    Value: '7'
  },
  {
    Field: 'City',
    Value: 'Some City'
  },
  {
    Field: 'Description',
    Value: 'Some Description'
  }
];

// #1 Mapping the array to an object...
let obj = {};
array.forEach(item => obj[item.Field] = item.Value);

// #2 Converting the object to JSON...
let json = JSON.stringify(obj);

console.log(json);

Bonus (ES6 + reduce):

const obj = array.reduce((acc, { Field, Value }) => ({ ...acc, [Field]: Value }), {});
like image 143
Maxime Gélinas Avatar answered Sep 29 '22 18:09

Maxime Gélinas


you can try the below approach . I have used spread operator(ES6) and Object.assign to create the object ,then converted it into json string.

        let SampleData = [
                { Field: 'Key', Value: '7'},
                { Field: 'City', Value: 'Some City'},
                { Field: 'Description', Value: 'Some Description'}
        ];
        
    let obj = Object.assign(...SampleData.map( x => Object.values(x)).map(y => ({[y[0]]: y[1]})));
    console.log(obj);
   //{ Key: "7", City: "Some City", Description: "Some Description" }
    console.log(JSON.stringify(obj));
like image 23
Niladri Avatar answered Sep 29 '22 20:09

Niladri


I had a similar requirement and here is how I achieved it.

var ranges: segmentRange[] = new Array(2);
ranges[0] = { minimumPercentage: 50, maximumPercentage: 60 };
ranges[1] = { minimumPercentage: 30, maximumPercentage: 40 };        
const segmentRanges = { segmentRanges: ranges };
return JSON.stringify(segmentRanges);

Output:

{"segmentRanges":[{"minimumPercentage":50,"maximumPercentage":60},{"minimumPercentage":30,"maximumPercentage":40}]}

HTH,

like image 24
Irfan Avatar answered Sep 29 '22 20:09

Irfan