5

Considering this example:

    if(this.plantService.plants[id])
    {
        if(this.plantService.plants[id].Name)
        {
            if(this.plantService.plants[id].Name[0])
                return this.plantService.plants[id].Name[0].value;
            else
                return '';
        }
        else
            return '';        
    }    
    return '';

I am wondering if it is possible to simplify what I am doing here.

My goal is to test the object-chain this.plantService.plants[id].Name[0] for validity.

However, if I just test if(this.plantService.plants[id].Name[0]) {...} exceptions are thrown.

Any proposals? :)

7
  • 2
    you could use the && operator in your if like this: if(this.plantService.plants[id] && this.plantService.plants[id].Name && this.plantService.plants[id].Name[0]){return this.plantService.plants[id].Name[0].value} else {return ''} Commented Nov 22, 2016 at 15:10
  • Please show us the exception thrown. you only say there is, but what is that? Commented Nov 22, 2016 at 15:10
  • 1
    @SuperCoolHandsomeGelBoy It would be a TypeError, as you'd be attempting to access a property on undefined. Commented Nov 22, 2016 at 15:11
  • @SuperCoolHandsomeGelBoy accessing variable of undefined Commented Nov 22, 2016 at 15:12
  • 2
    You could catch the exception. Commented Nov 22, 2016 at 15:12

3 Answers 3

4

You could reduce the array with the object, after checking value and type.

function getIn(object, keys, def)  {
    return keys.reduce(function (o, k) {
        return o && typeof o === 'object' && k in o ? o[k] : def;
    }, object);
}

var object = { plantService: { plants: [{ Name: [{ value: 42 }] }] } };

console.log(getIn(object, ['plantService', 'plants', 0, 'Name', 0, 'value'], 'default value'));
console.log(getIn(object, ['b', 'c', 'd', 'e'], 'default value'));

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

1 Comment

Probably the nicest way for me... nevertheless I hoped there was something nicer :)
2

You could write a simple function on your own like,

function getVal(obj, propQueue, defaultValue) {
  for (var prop of propQueue) {
    if ((obj = obj[prop]) === undefined) {
      break;
    }
  }

  return obj || defaultValue;
}

Now you can call it like,

var value = getVal(this, ["plantService", "plants", id, "name" 0], "");
console.log(value); //either "" or the real value.

Comments

0

You can try this:

if(this.plantService.plants[id] && this.plantService.plants[id].Name && this.plantService.plants[id].Name[0]){
        return this.plantService.plants[id].Name[0].value;

        }else{

    return '';
}

Or maybe your problem is that your model is not complete and you need to be sure of that in order to prevent these validations and replace with this:

return this.plantService.plants[id].Name[0].value;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.