Home > Software engineering >  creating dynamically named variables in javascript
creating dynamically named variables in javascript

Time:07-08

I am trying to create a JSON object using dynamic names for its fields. The idea is to create a JSON like this one (example with 4 agents):

{
    "Agent_1":[549,871,967,701,42],
    "Agent_2":[615,683,663,638,190],
    "Agent_3":[578,343,646,42,599],
    "Agent_4":[42,779,21,856,578]
}

My problem is I don't know how to create those names for the fields. This is my code:

// Creates the structure for a JSON file
export const buildJSON = (_oldChain, agents, resources) => {
    let object = {};
    let names;
    for(let i = 0; i < agents; i  ){
        let agentVector = [];
        names = "Agent_"   i;
        for(let j = 0; j < resources; j  ){
            agentVector[j] = parseInt(_oldChain[i][j]);
        }
        object.names = agentVector;
    }
    return JSON.stringify(object);
}

As you can see, for each iteration, I create a variable "Agent_" i. But now, how can I use those names when I am creating my object, here: object.names = agentVector?

CodePudding user response:

You can set properties with dynamic names on objects by using bracket notation:

const obj = {};
obj['foo'] = 'bar';
const something = 'baz';
obj[something] = 'qux';

console.log(obj);
// {
//    foo: "bar",
//    baz: "qux"
// }

So in your example, it would be:

object[names] = agentVector;

CodePudding user response:

You can directly assign value to Objects by keeping your newly created variable as key, like:

object[names] = agentVector;
  • Related