Keren Keren - 4 months ago 7
jQuery Question

How to add new key value pair into existing object

I have a simple function:

function pagination(opt, limit){
console.log(opt);
//logs out this-> [Object { limit="2", layout="getConversations"}]

if (typeof opt === 'object') {
var list = {
data: [opt]
}
list.data['limitstart'] = 24; //undefined
console.debug(data); //here it should list three key value pairs including limitstart which just added
}
}


I tried this:

list.data.push({ 'limitstart': 24 }); //creates another object.


expected output:

[Object { limit="2", layout="getConversations", limitstart=24}]

Answer

You can set it as string, as in your example, but as you put the object in an array with [obj], you have to select the index 0 too:

list.data[0]["limitstart"] = 24;

Or you can do it as a property:

list.data[0].limitstart = 24;

Working example.

For your exprected output you don't have to put the obj in an array:

var obj = {limit: '2', layout: 'getConversations'};
var list = {data: obj};

list.data.limitstart = 24;
console.debug(list.data); // you have to log 'list.data' not 'data'
Comments