Typescript将数组转换为JSON [英] Typescript convert an array to JSON

查看:589
本文介绍了Typescript将数组转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复杂的数据结构,我需要将其转换为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'}
];

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

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

我的真实代码中的字段和数据是对象内的结构,所以我无法在工作范围内简单地使用Object.create()或Object.assign().

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.

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

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. 将数组映射到对象
  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);

这篇关于Typescript将数组转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆