TypeScript将数组转换为JSON

10

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

例如,我有以下内容(从我的代码库简化而来):

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

基本上,我的数据是一个数组,其中第一个元素是数据库列名,第二个元素是该列中的数据。我试图得到一个JSON对象,它应该是:

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

我的实际代码中有字段和数据结构在对象内部,所以我不能简单地使用Object.create()或Object.assign(),就我所知道的而言。

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


1
尝试这样做:将数组映射到对象上 var obj = {}; array.forEach(item => obj[item.Field] = item.Value);,然后将对象转换为 JSON 格式 JSON.stringify(obj) - Maxime Gélinas
1
谢谢,解决了。如果您将此作为答案发布,我可以接受它。您确实在下面的答案之前得到了这个结果,那个答案也是有效的。 - Steven Scott
@SevenScott 很高兴能帮到你!我刚刚发布了我的答案。 - Maxime Gélinas
3个回答

23

根据您的要求,以下是操作步骤:

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

奖金计算(ES6 + reduce):

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

1

我有一个类似的需求,这是我如何实现它的方法。

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

输出:

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

祝好,


1

您可以尝试以下方法。我使用了扩展运算符(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));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接