Typescript将数组转换为JSON

编程入门 行业动态 更新时间:2024-10-28 14:33:36
本文介绍了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:

  • 将数组映射到对象
  • 将对象转换为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

    本文发布于:2023-10-28 23:00:50,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1538013.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:数组   转换为   Typescript   JSON

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!