0

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?

8
  • "associative JS array" === JS Object. Commented Apr 11, 2017 at 9:13
  • 1
    "standard JS/jQuery construct"... jQuery is not a language. Commented Apr 11, 2017 at 9:14
  • First its a JS Object. Second, you do not have subarrays. You have nested objects. Third, yes you can use for..in to loop over properties of an object Commented Apr 11, 2017 at 9:15
  • var aquatic = ["fish", "turtle"].map(key => zoo[key]) Commented Apr 11, 2017 at 9:17
  • @evolutionxbox: I never said jQuery would be a language :-) And I know that "associative array" is actually an object. Anyway, for JS non-professionals like me, associative array is a more explicit term, that's why I used it. JS objects behave pretty much like associative arrays. But if my terminology offends you, I can surely edit the text. Just let me know. Commented Apr 11, 2017 at 9:44

1 Answer 1

5

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)

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

9 Comments

Yay! An answer with no for loop!
@evolutionxbox: No for loop, but make no mistake, .map is still a loop.
@Cerbrus sure, but only in a recursive function sense.
You can see what map() is doing in developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Polyfill, it is using while loop.
@NenadVracar again sure, but it can also be written without a for/do/while loop.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.