0

I have this code:

function my_json_function(my_variable) {
    var json_var = {
        my_variable: [{
            "firstName": "John",
            "lastName": "Doe"
        }, {
            "firstName": "Anna",
            "lastName": "Smith"
        }]
    };

    return json_var;
}

So, the problem is:

I pass to the function a variable named my_variable, and I want to assign it to the name of the json group.

So, I explain what I mean: For example if my_variable = "employees", the function have to produce the following result:

"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"}
]

I've tried to casting like this: String(my_variable), but it return me the error:

Uncaught SyntaxError: Unexpected token :

where am I wrong? thanks

3 Answers 3

3

You'll need to use an assignment with brackets instead:

var json_var = {};
json_var[my_variable] = [
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna",    "lastName":"Smith"}
];

Inside the object literal it isn't possible to have a dynamic key name based.

Sign up to request clarification or add additional context in comments.

3 Comments

this is not what he wants, he first needs to clone the old data
@Vorge What do you mean?
For example if my_variable = "employees", the function have to produce the following result:
2

See the comments inline in the code:

function my_json_function(my_variable) {
    var json_var = {
        peoples: [{
            "firstName": "John",
            "lastName": "Doe"
        }, {
            "firstName": "Anna",
            "lastName": "Smith"
        }]
    };

    var obj = {}; // Create empty object
    obj[my_variable] = json_var.peoples; // Assign the data  in the new key

    return obj; // return newly created object
}

Comments

0

You need to use bracket notation rather than dot notation.

function my_json_function(my_variable) {
    var json_var = {};
    json_var[my_variable] = [{
        "firstName": "John",
        "lastName": "Doe"
    }, {
        "firstName": "Anna",
        "lastName": "Smith"
    }];

    return json_var;
}

Note the use of json_var[my_variable] with square brackets. This will create a property in the object with whatever variable is passed in.

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.