Search code examples
javascriptobjectobject-literal

How can I add a key/value pair to a nested object literal?


SOLVED, the function this code exists in is being called more often then expected, due to this the values can be undefined and therefor the adding values to the nested object literal won't work. My solution was to check whether the response.times is defined and only in this case add the values.

I'm currently having a bit of trouble where I'm trying to add key-value pairs to an object within a javascript object.

I mainly looked at the solutions in the following topic, because I couldn't find anything closer to my question.

How can I add a key/value pair to a JavaScript object?

I'm in a situation where I get an object returned with a bunch or executiontimes which I use in order to determine where my application gets slow (server, database, query etc.). However all of these times have been present in the response object which is passed from the server.

In order to change this I made a specific object within the response for all of these times. The problem is I still add all of these timestamps to the main response object before I change them into this object.

response.times = {
  'executionTime': response.executionTime,
  'processingTime': response.processingTime,
}

I would like to be able to add of all these timestamps to this object as soon as they are known.

Adding the values to the response object can be done in multiple ways:

response.executionTime = 'x';
response['executionTime'] = 'x';
Object.assign(response, {executionTime: 'x'});
response.push({executionTime: 'x'});

But none of these methods work in a case where I'm trying to do something like this, the errors I'm getting in these codes are Cannot read property ... of undefined . In all of the cases times seems undefined even though there are values set to it.

response.times.executionTime = 'x';
response.times['executionTime'] = 'x';
Object.assign(response.times, {executionTime: 'x'});
Object.assign(response['times]', {executionTime: 'x'});
response.times.push({executionTime: 'x'});
response['times'].push({executionTime: 'x'});

Is there a correct way to get this done?


Solution

  • Ensure response and response.times are objects or empty objects instead of null, undefined, ... :

      var response;
      response = response || {};
      response.times = response.times || {};
      response.times.executionTime = 'x';
      console.log(response);