typescript 打字稿将数组转换为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48101176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:09:11  来源:igfitidea点击:

Typescript convert an array to JSON

jsontypescript

提问by Steven Scott

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.

我有一个需要转换为 JSON 的复杂数据结构。问题是我的字段名称和值都在一个数组中。

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:

基本上我的数据是一个数组,其中第一个元素是数据库列名,第二个元素是列中的数据。我正在尝试获取一个 JSON 对象:

{ 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.

我的真实代码具有对象中的字段和数据结构,因此我不能简单地使用 Object.create() 或 Object.assign() 就可以工作。

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.

我尝试循环构建一个简单的字符串,然后使用 JSON.parse 将其分解,但这对于我认为会更简单的东西来说似乎是很多开销。

回答by Maxime Gélinas

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

正如你所问,这是如何做到的:

  1. Mapping the array to an object
  2. Converting the object to JSON
  1. 将数组映射到对象
  2. 将对象转换为 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):

奖励(ES6 + 减少):

const obj = array.reduce((acc, { Field, Value }) => ({ ...acc, [Field]: Value }), {});

回答by Niladri

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.

你可以试试下面的方法。我使用了扩展运算符(ES6)和 Object.assign 来创建对象,然后将其转换为 json 字符串。

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

回答by Irfan

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}]}

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

HTH,

哈,