Home > Software design >  Create Json with specific structure from two different arrays in javascript
Create Json with specific structure from two different arrays in javascript

Time:08-24

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:

Let's say we have 2 arrays: one containing "keys" and another one containing "values"

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:

[{
        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!

CodePudding user response:

Here's one way to get your desired 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:

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 (e.g. 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.)

  • Related