<!DOCTYPE html>
<html>
<head>
<meta name="description" content="reduce - safe nested object inspection">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-javascript">
var luke = {
name: 'luke',
jedi: true,
parents: {
father: {
jedi: true
},
mother: {
jedi: false
}
}
};
var han = {
name: 'han',
jedi: false,
parents: {
father: {
jedi: false
},
mother: {
jedi: false
}
}
};
var anakin = {
name: 'anakin',
jedi: true,
parents: {
mother: {
jedi: false
}
}
};
var characters = [luke, han, anakin];
function fatherWasJedi(character) {
var path = 'parents.father.jedi';
return path.split('.').reduce(function(obj, field) {
if(obj) {
return obj[field];
} else {
return false;
}
}, character);
}
characters.forEach(function(character) {
console.log(character.name + ' father was a jedi: ' + fatherWasJedi(character));
});
</script>
<script id="jsbin-source-javascript" type="text/javascript">var luke = {
name: 'luke',
jedi: true,
parents: {
father: {
jedi: true
},
mother: {
jedi: false
}
}
};
var han = {
name: 'han',
jedi: false,
parents: {
father: {
jedi: false
},
mother: {
jedi: false
}
}
};
var anakin = {
name: 'anakin',
jedi: true,
parents: {
mother: {
jedi: false
}
}
};
var characters = [luke, han, anakin];
function fatherWasJedi(character) {
var path = 'parents.father.jedi';
return path.split('.').reduce(function(obj, field) {
if(obj) {
return obj[field];
} else {
return false;
}
}, character);
}
characters.forEach(function(character) {
console.log(character.name + ' father was a jedi: ' + fatherWasJedi(character));
});</script></body>
</html>