peterschussheim
10/13/2016 - 9:21 PM

safe object inspection using reduce

safe object inspection using reduce

var luke = {
  name: "luke skywalker",
  jedi: true,
  parents: {
    father: {
      jedi: true
    },
    mother: {
      jedi: false
    }
  }
};

var han = {
  name: "han solo",
  jedi: false,
  parents: {
    father: {
      jedi: false
    },
    mother: {
      jedi: false
    }
  }
};

var anakin = {
  name: "anakin skywalker",
  jedi: true,
  parents: {
    mother: {
      jedi: false
    }
  }
};

var characters = [luke, han, anakin];

function fatherWasJedi(character) { //////transforms path into an array of strings
	var path = "parents.father.jedi";
	return path.split(".").reduce(function(obj, field) {
        if (obj) {
            return obj[field];
        }
        return false;
    }, character);
}

var result = characters.forEach(function(character) {
  console.log(character.name + "'s father was a jedi:", fatherWasJedi(character));
});

safe object inspection using reduce

This Gist was automatically created by Carbide, a free online programming environment.

You can view a live, interactive version of this Gist here.