Is it possible to append value in an existing object - jquery

10,015

Solution 1

There are several ways to do it;

Plain javascript:

var req = { "term" : "s" };
req.st_id = "512";

Because javascript objects behaves like associative arrays* you can also use this:

var req = { "term" : "s" };
req["st_id"] = "512";

jQuery way $.extend():

var req = { "term" : "s" };
$.extend(req, { "st_id" : "512" });

Solution 2

You can do this in a couple of ways:

req.st_id = "512";

or

req["st_id"] = "512";

The second of these is especially useful if the variable name is dynamic, e.g. a variable could be used instead of the string literal:

var key = "st_id";
req[key] = "512";

Solution 3

Yes this is possible, to add properties to a value simply use the following syntax:

req.st_id = "512";
Share:
10,015
Fero
Author by

Fero

C00L Developer....

Updated on June 04, 2022

Comments

  • Fero
    Fero almost 2 years

    Consider i am having an object "req".

    When i use console.log(req) i get

    Object { term="s"}
    

    My requirement is to append an value with the existing object.

    My expected requirement is to be like this:

    Object { term="s", st_id = "512"}
    

    Is it possible to do the above?

    If yes, how ?

    Thanks in advance..