问题
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}]
回答1:
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'
回答2:
To get the output as you require you don't need to place opt
in to an array, you simply need to add a property to it, like this:
function pagination(opt, limit) {
console.log('input', opt);
if (typeof opt === 'object') {
opt.limitstart = 24; // add the property here
}
console.log('output', opt);
}
pagination({
limit: '2',
layout: 'getConversations'
});
来源:https://stackoverflow.com/questions/38608990/how-to-add-new-key-value-pair-into-existing-object