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?

3
  • Found what broke it Object was empty not null Commented Apr 22, 2014 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 :) Commented Apr 22, 2014 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). Commented Apr 22, 2014 at 18:58

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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…}

1 Comment

Found what broke it Object was empty not null

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.