lisovaccaro
lisovaccaro

Reputation: 33956

Append value to object on certain condition?

I'm trying to append a value only if a condition is met (distance != "off").

This is what I tried but I cannot get it to work?

var params = {
    q: pizza,
    result_type: "mixed",
    include_entities: "true",
    if(distance != "off") {
        geocode: geolocation,
        }
    rpp: 15,
    page: 1
};

How can it be done?

Upvotes: 1

Views: 87

Answers (2)

Rob Stevenson-Leggett
Rob Stevenson-Leggett

Reputation: 35679

Tou have two options with different implications.

Option 1:

var params = {
    q: pizza,
    result_type: "mixed",
    include_entities: "true",
    geocode: (distance != "off") ? geolocation:null,
    rpp: 15,
    page: 1
};

or Option 2:

var params = {
    q: pizza,
    result_type: "mixed",
    include_entities: "true",
    rpp: 15,
    page: 1
};

if(distance != "off") {
    params.geocode: geolocation;
}

Option 1 would mean geocode is defined and you'd need to check for null or whatever you decide the default value should be. Option 2 would mean that geocode is undefined, which is what you suggest you would like to do with your original code example.

Upvotes: 3

copy
copy

Reputation: 3372

var params = {
    q: pizza,
    result_type: "mixed",
    include_entities: "true",
    rpp: 15,
    page: 1
};

if(distance != "off") {
    params.geocode = geolocation;
}

Upvotes: 1

Related Questions