Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Using JavaScript/jQuery methods on array of objects?

I have an array of Objects in JavaScript and I'm having trouble accessing JS methods on my array.

Is there a way to use methods such as removeClass or attr on an array without having to use a for loop? For example, in jQuery if I do $("li.listing").removeClass("listing")....it will remove the listing class from all li tags where this class is present.

Is there a way without having to use multiple for loops, to use these methods on an array (so that it looks at each element/object in the array)?

Example

cars.removeClass("listing") // Remove listing class from every element in cars array - is this syntax or something similar possible? Thanks!

Array index [0] example

0: m.fn.init [
 li#listing-MCMR-R-ZT-BFNT001-ZT-BFNT001.listing.filtered-out-by-car-type.listing-filtered-out, 
 prevObject: m.fn.init(1), 
 context: car, 
 selector: "li.listing"
]

Answer*

Draft saved
Draft discarded
Cancel
6
  • 1
    I'm not sure, but wouldn't .forEach be preferable over .map if you're not returning the array? Commented Apr 18, 2018 at 18:14
  • depends on the desired result for sure! I suppose in this specific case forEarch could be preferable. Either way, one of the two methods is the correct way to go Commented Apr 18, 2018 at 18:18
  • Do you know if there is a performance difference between .forEach and an actual for loop? Commented Apr 18, 2018 at 18:23
  • theoretically forEach is a bit slower due to the overhead of calling a function on every single loop (good explanation here stackoverflow.com/a/43821929/1148244), but practically speaking the difference should be insignificant. forEach provides good readability and prevents you from dealing with extra variables, though you should be good to use either one Commented Apr 18, 2018 at 18:27
  • no problem! be sure to accept the answer if it solved your problem so future readers can benefit :) Commented Apr 18, 2018 at 18:30

lang-js

AltStyle によって変換されたページ (->オリジナル) /