Reputation: 359
Lets have an example JS object (aka "associative array"):
var zoo = {
monkey: { legs: 4, color: "black" },
fish: { legs: 0, color: "yellow" },
turtle: { legs: 4, color: "green" },
emu: { legs: 2, color: "gray" },
};
Now I want to retrieve a nested object (aka "subarray") of aquatic animals. Is there a standard JS/jQuery construct or function to filter object properties by array ("index an array by array"), i.e. something like:
var aquatic = zoo["fish", "turtle"];
The result should obviously be { { legs: 0, color: "yellow" }, { legs: 4, color: "green" } }
.
Or is a for
loop the simplest solution here?
Upvotes: 0
Views: 764
Reputation: 122037
You can use map()
and return array of objects.
var zoo = {
monkey: { legs: 4, color: "black" },
fish: { legs: 0, color: "yellow" },
turtle: { legs: 4, color: "green" },
emu: { legs: 2, color: "gray" },
};
var aquatic = ["fish", "turtle"];
var result = aquatic.map(e => zoo[e]);
console.log(result)
Upvotes: 5