简体   繁体   中英

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.

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 }), {});

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));

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM