Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over Object Literal Values

Tags:

javascript

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"; } 
like image 562
Aaron Avatar asked Feb 20 '12 00:02

Aaron


People also ask

How do you iterate through object literals?

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!

How do you iterate the value of a object?

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.

Can you iterate over an object?

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.


2 Answers

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]); }); 
like image 133
Petah Avatar answered Oct 07 '22 23:10

Petah


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

like image 40
Blair Anderson Avatar answered Oct 07 '22 23:10

Blair Anderson