最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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..

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..

Share Improve this question edited Nov 30, 2011 at 13:48 Emre Erkan 8,4823 gold badges51 silver badges54 bronze badges asked Nov 30, 2011 at 13:36 FeroFero 13.3k46 gold badges118 silver badges159 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 14

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" });

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";

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

req.st_id = "512";
发布评论

评论列表(0)

  1. 暂无评论