我有一个复杂的数据结构,我需要将其转换为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:
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
发布评论