How to add new key value pair into existing object

萝らか妹 提交于 2021-01-27 06:40:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!