简体   繁体   English

从 javascript 中的两个不同 arrays 创建具有特定结构的 Json

[英]Create Json with specific structure from two different arrays in javascript

I've already tried to find a solution on stack, but I didn't found a possible reply, so I decided to open a topic to ask:我已经尝试在stack上寻找解决方案,但没有找到可能的回复,所以我决定开个话题问问:

Let's say we have 2 arrays: one containing "keys" and another one containing "values"假设我们有 2 个 arrays:一个包含“键”,另一个包含“值”

Example:例子:

keys = [CO2, Blood, General, AnotherKey, ... ]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[... [

I have to create a Json with a specific structure like:我必须创建一个具有特定结构的 Json,例如:

[{
        name: 'CO2',
        data: [2,5,4,6]
    }, {
        name: 'Blood',
        data: [4,5,6]
    }, {
        name: 'General',
        data: [1,3,34.5,43.4]
    }, {
         ...
    }, 
}]

I've tried to make some test bymyself, like concatenate strings and then encode it as json , but I don't think is the correct path to follow and a good implementation of it... I've also take a look on JSON.PARSE , JSON.stringify , but I never arrived at good solution so... I am asking if someone know the correct way to implements it!我尝试自己进行一些测试,例如连接字符串,然后将其编码为 json ,但我认为这不是正确的路径和一个很好的实现......我也看看JSON.PARSEJSON.stringify ,但我从来没有找到好的解决方案,所以......我问是否有人知道实现它的正确方法!

Here's one way to get your desired output:这是获得所需 output 的一种方法:

 keys = ["CO2", "Blood", "General", "AnotherKey"] values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ] const output = keys.map((x, i) => { return {"name": x, "data": values[i]} }) console.log(output)

However, since you're literally constructing key/value pairs, you should consider whether an object might be a better data format to output:但是,由于您实际上是在构建键/值对,因此您应该考虑 object 是否可能是比 output 更好的数据格式:

 keys = ["CO2", "Blood", "General", "AnotherKey"] values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ] const output = {} for (let i=0; i<keys.length; i++) { output[keys[i]] = values[i] } console.log(output)

With this data structure you can easily get the data for any keyword (eg output.CO2 ).使用此数据结构,您可以轻松获取任何关键字的数据(例如output.CO2 )。 With your array structure you would need to iterate over the array every time you wanted to find something in it.使用您的数组结构,每次您想在其中找到一些东西时,您都需要遍历数组。

(Note: The reason you weren't getting anywhere useful by searching for JSON methods is that nothing in your question has anything to do with JSON; you're just trying to transform some data from one format to another. JSON is a string representation of a data object.) (注意:通过搜索 JSON 方法,您没有得到任何有用的原因是您的问题与 JSON 无关;您只是试图将一些数据从一种格式转换为另一种格式。Z0ECD11C1D7A287A2F8D 表示 1数据 object。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM