【问题标题】:Typescript convert an array to JSON打字稿将数组转换为 JSON
【发布时间】:2018-06-14 12:46:45
【问题描述】:

我有一个复杂的数据结构,需要将其转换为 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 将其拆分,但这对于我认为更简单的事情来说似乎有很多开销。

【问题讨论】:

  • 试试这个:将数组映射到对象var obj = {}; array.forEach(item => obj[item.Field] = item.Value);,然后将对象转换为json JSON.strignify(obj)
  • 谢谢,成功了。如果您将此作为答案发布,我可以接受。您确实在下面的答案之前得到了这个,这也有效。
  • @SevenScott 很高兴为您提供帮助!我刚刚发布了我的答案。

标签: json typescript


【解决方案1】:

如你所问,方法如下:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      我也有类似的要求,这就是我实现它的方法。

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

      HTH,

      【讨论】:

        猜你喜欢
        • 2020-12-27
        • 2018-04-26
        • 2021-12-19
        • 2016-09-10
        • 2018-09-18
        • 1970-01-01
        • 2017-12-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多