Home > Software design >  How to write dynamic json object inside an array in javascript
How to write dynamic json object inside an array in javascript

Time:09-21

Desired output--

[
  {
    "group1": {
      "Token1": "123443423",
      "Token2": "121414141"
    },
    "group2": {
      "Token1": "123443423",
      "Token2": "121414141"
    }
  }
]

Group1 and group2 is dynamic and also the token1 and token2 value is dynamic. So i write this way --

[ {`${group1}`:{ 
         "Token1" : `${token1}`,
         "Token2" : `${token2}`
              },
        `${group2}`:{ 
         "Token1" : `${token1}`,
         "Token2" : `${token2}`
              }
 }]

But ${group1} shows error unexpected token ` (template literate).

CodePudding user response:

1. [Specific]

// helper function
function createGroup(groupName, token1, token2) {
  const group = {};
  group[groupName] = {
    Token1: token1,
    Token2: token2
  };
  return group;
}

//and then create a result output
var result = [
  createGroup('group1', group1token1, group1token2),
  createGroup('group2', group2token1, group2token2),
]

2. [More general] For multiple paramenters (more than fixed 2):

your parametersObject have to be as:

{
  Token1: 'token_1_value_here',
  Token2: 'token_2_value_here',
  ...
  ParameterN: 'parameter_n_value_here',
  ...
}

And then:

// helper function 2
function createGroup(groupName, parametersObject) {
  const group = {};
  group[groupName] = parametersObject;
  return group;
}

//and then create a result output
var result = [
  createGroup('group1', group1parametersDto),
  createGroup('group2', group2parametersDto)
]

CodePudding user response:

in your way you can create object with variables value this way . there was syntax error in your approach, template literals are not allowed for object key inside object directly

var group = "group",
      Token1 = "123443423",
      Token2 = "121414141"
var newObject = 
{
  [group   "1"] : {Token1 , Token2},
  [group   "2"] : {Token1 , Token2},
  [group   "3"] : {Token1 , Token2},
  [group   "4"] : {Token1 , Token2}    
}
console.log(newObject)

there is also more easy way to do same which is more conveneint example below

var object = {},
    Token1 = "123443423",
    Token2 = "121414141"

object["group1"] = {Token1,Token2}
object["group2"] = {Token1,Token2}
object["group3"] = {Token1,Token2}

console.log(object)

  • Related