0

I have this javascript Object named group.

I am trying to add another object into this called Rule if the group.Rule object is null. My code is like so:

var ruleObj = { 
    Id: null, 
    RuleId: null, 
    MatchLogic: 0, 
    Min: null, 
    Max: null, 
    TagIds: null 
};

group.Rule = group.Rule == null ? group.Rule = ruleObj : group.Rule;

I would think that group.Rule = ruleObj would do it but console logging it shows that group.Rule is {} empty.

How do I add the group.Rule object onto group?

Tom
  • 7,640
  • 1
  • 23
  • 47
allencoded
  • 7,015
  • 17
  • 72
  • 126
  • Found what broke it Object was empty not null – allencoded Apr 22 '14 at 18:52
  • Your ternary operator should only include one assignment: `group.Rule = group.Rule == null ? ruleObj : group.Rule;` — more succinctly you could use an or operator (`||`): `group.Rule = ruleObj || group.Rule`. This won't resolve your problem though :) – Barney Apr 22 '14 at 18:55
  • Write out your solution as an answer and mark it as accepted for the benefit of others — you might also consider using a library like Underscore or Lodash for utilities like `isEmpty` (and `extend`, which could probably help with higher-level problems). – Barney Apr 22 '14 at 18:58

2 Answers2

0

It should work this way as you said:

var group = {};

var ruleObj = { Id: null, RuleId: null, MatchLogic: 0, Min: null, Max: null, TagIds: null};
group.Rule = group.Rule == null ? ruleObj : group.Rule;

console.log(group.Rule);

I set up an online demo here: http://jsfiddle.net/2YKTX/

And in the console I see:

Object {Id: null, RuleId: null, MatchLogic: 0, Min: null, Max: null…}
vtortola
  • 34,709
  • 29
  • 161
  • 263
0

A more efficient assignment would be:

group.Rule || (group.Rule = ruleObj);

instead of

group.Rule = group.Rule == null ? group.Rule = ruleObj : group.Rule;

However, note that {} != null (an empty object is truthy), so if you initialized Rule to an empty object, you'll need to change your assignment test.

Stepan Riha
  • 1,736
  • 14
  • 12