javascript - JSON How to return an objects name instead of its value -
json objects have "name : value" relationship. need way return objects name instead of value.
for example, if animals[0].species return value "feline", how instead return name "species"?
the function i'm writing requires me check if objects name equal input of function before return value of object.
i have searched stackoverflow , w3schools solution, no success.
var animals = [ { "animal": "cat", "species": "feline", "likes": "yarn", "dislikes" : "water" }, { "animal": "dog", "species": "canine", "likes": "rubber balls", "dislikes": "thunder" } ]; function lookup(property){ if (animals[0].property == "species") { return animals[0].species; } } lookup("species");
you're missing quotes around species
function lookup(property) { if (animals[0].property === 'species') { // see quotes ? return animals[0].species; } }
that function using animals
free variable , not useful if ever plan on using lookup
on other object. writing function differently, can make more versatile
function lookup(object, property) { if (object.hasownproperty(property)) { return object[property]; } return null; }
now specific animal
lookup(animals[0], 'species'); // => 'feline' lookup(animals[1], 'species'); // => 'canine' lookup(animals[2], 'species'); // => null
you can take 1 step further defining higher-order procedure
function getspecies(animal) { return lookup(animal, 'species'); } getspecies(animal[0]); // => 'feline' getspecies(animal[1]); // => 'canine' getspecies(animal[2]); // => null
per alex's comment, last part, use partial function application or curry lookup
function.
const lookup = x => y => y.hasownproperty(x) ? y[x] : null; const species = lookup('species'); species(animal[0]); // => 'feline' species(animal[1]); // => 'canine' species(animal[2]); // => null
Comments
Post a Comment