nachol
nachol

Reputation: 17

Create a JSON object with variables as fields

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?

Upvotes: 1

Views: 316

Answers (2)

chad.delorean
chad.delorean

Reputation: 31

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"} ]

Upvotes: 0

WakeskaterX
WakeskaterX

Reputation: 1418

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?

Upvotes: 2

Related Questions