Reputation: 201
I created an object. But when I try to set some values in it an error is thrown. See code below:
function CheckStatus(oldJob, newJob) {
var obj = {};
if(newJob && newJob.Status) {
if (oldJob.Status.total !== newJob.Status.total) {
obj.Status.total = newJob.Status.total;
}
if (oldJob.Status.charge_description && oldJob.Status.charge_description !== newJob.Status.charge_description) {
obj.Status.charge_description = newJob.Status.charge_description;
}
}
}
TypeError: Cannot set property 'total' of undefined
Upvotes: 0
Views: 112
Reputation: 339
Your obj variable has nos property status ! you must create his real structure before !
use lodash _.set :
const _ = require('lodash');
function CheckStatus(oldJob, newJob) {
let obj = {};
if (newJob && newJob.Status) {
if (oldJob.Status.total !== newJob.Status.total) {
_.set(obj, 'Status.total', newJob.Status.total);
}
if (oldJob.Status.charge_description && (oldJob.Status.charge_description !== newJob.Status.charge_description)) {
_.set(obj, 'Status.charge_description', newJob.Status.charge_description);
}
}
}
FYI it return a mutated object not a new object ! ;)
Upvotes: 0
Reputation: 1512
Well your definition of obj
is an empty object. So before setting obj.Status.total
you need to define obj.Status
, either in the original declaration like so:
var obj = {
Status: {}
}
or later like so:
obj.Status = {}
Upvotes: 2