1

I want to create a JSON object with variables as associative variable names similar to the following:

var field = 'first';
var query = { details.field, details.field };

I would prefer if the details were a fixed value.

This is my dataset currently

{
    field1: ,
    group: {
        first:
    }
}

My question is, how would I go about creating JSON objects with variables as fields?

2 Answers 2

2

You can add a property to an object like so:

var query = { details: {} };
var field = 'first';

query.details[field] = "TEST";

Which will give you the object:

{ details: { first: "TEST" }}

which you can then access with query.details.first or query.details[field];

Is that what you're looking for?

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

Comments

0

A simple way to accomplish this in Javascript is using the . operator.

query.details.field = "first";

This will product an object as follows:

"query" { "details" { "field": "first"} }

Is this what your looking for?

If you want multiple details you will want to use an array.

var query = [];
query.push({"details" { "field" : "first"} });
query.push({"details" { "field" : "second"} });

This will product an object like this "query" [ "details" { "field" : "first"}, "details" { "field" : "second"} ]

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.