0

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?

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Tysm! Nice explanation :)
1

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

object[names] = agentVector;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.