如何将新键值对添加到现有对象中

时间:2016-07-27 09:28:46

标签: jquery object

我有一个简单的功能:

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

我试过了:

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

预期产出:

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

2 个答案:

答案 0 :(得分:1)

您可以将其设置为字符串,如您的示例所示,但是当您将对象放入包含[obj]的数组时,您还必须选择索引0

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

或者您可以将其作为财产:

list.data[0].limitstart = 24;

<强> Working example.

对于您的表达式输出,您不必将obj放入数组中:

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'

答案 1 :(得分:1)

要根据需要获取输出,您不需要将opt放入数组中,只需添加一个属性,如下所示:

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