I have a standard jQuery plugin set up that creates default settings at the top:
jQuery.fn.myPlugin = function(options) { var defaults = { starts: "0px,0px", speed: 250, ... }; o = $.extend(defaults, options); }
I have another variable called numberOfObjects
.
I'm trying to loop through the default variables. For each object found (from numberOfObjects
) I need to duplicate the value of the variable value. So, if the numberOfObjects
variable is 3, the defaults.starts
should be 0px,0px > 0px,0px > 0px,0px
. The & gt; is used to split values.
This is what I currently have. X
represents the variable name inside defaults. Y
represents the variable for the current value of x
. I've gotten this far and have no clue what to do next.
for (x in defaults) { // x is defaults.x defaults.x = defaults.x + " > y"; }
The Object. keys() method requires you to pass in to it an Object, and from that it will return an array of all the keys in that object. After this, you can begin to use any array method that you'd like to iterate over it and interact however you'd like. You can use a forEach, a map, a filter, or even a reduce!
Object. It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys). After which you can use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.
There are two methods to iterate over an object which are discussed below: Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object.
var obj = { 'foo': 1, 'bar': 2 }; for (var key in obj) { console.log(obj[key]); }
Or with jQuery:
$.each(obj, function(key, value) { console.log(this, value, obj[key]); });
You should not have to depend on jQuery for this.
Object.keys(obj).forEach(function (key) { var value = obj[key]; // do something with key or value });
Mozilla Developer documentation - https://developer.mozilla.org
Polyfill for old browsers
View Performance Results - https://jsperf.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With