How to add a new pair of key values ​​to an 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}]
+4
source share
2 answers

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

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

Or you can do it as a property:

list.data[0].limitstart = 24;

Working example.

For your correct output, you do not need to put objin 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'
+1
source

To get the result as needed, you do not need to put it optin an array, you just need to add a property to it, for example:

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'
});
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1649263/


All Articles