Iterate over Object Literal Values

Javascript

Javascript Problem Overview


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";
}

Javascript Solutions


Solution 1 - Javascript

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]);
});

Solution 2 - Javascript

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
});

Solution 3 - Javascript

Let's setup our basic object before we get started:

const x = {
  x: 1,
  y: 2,
  z: 3
};

We can use Object.keys(x) to return an array of all of the keys within our object.

Object.keys(x)
> ['x', 'y', 'z']

Now we able to map, filter, reduce and loop over our array and do something with that value within our object:

Object.keys(x).map(key => x[key] + 1)
> [2,3,4]

Object.keys(x).forEach(key => console.log(x[key]))
> [1,2,3]

The main take away here is that we have to use the key to access that specific value, it works but it feels a little clunky. ES2017 brings with it Object.values() which can be used as a nice shortcut for returning an array of all of the values within an Object.

Object.values(x)
> [1,2,3]

Object.values(x).map(value => value + 1)
> [2,3,4]

Object.values(x).forEach(value => console.log(value))
> [1,2,3]

You can read more about Object.values() at MDN, they also include a polyfill, should you need to support older browsers & browsers which haven't yet implemented it.

There's also Object.entries() which conveniently allows you to access the keys and the values. It returns an array containing arrays (first item being the key and the second item being the value.

Object.entries(x);
> [['x', 1], ['y', 2], ['z', 3]]

We can use de-structuring to easily get at these values:

Object.entries(x).map(([key, value]) => console.log(key, value))

Solution 4 - Javascript

To iterate over an object's values you can use a for...of loop with Object.values.

const myObj = {a: 1, b: 2}

for (let value of Object.values(myObj)) {
    console.log(`value=${value}`)
}

// output: 
// value=1
// value=2

If you want the key and value when iterating, you can use Object.entries.

const myObj = {a: 1, b: 2}

for (let [key, value] of Object.entries(myObj)) {
    console.log(`key=${key} value=${value}`)
}

// output: 
// key=a value=1
// key=b value=2

Solution 5 - Javascript

Best practice is to validate if the object attribute that is being iterated over is from the object itself and not inherited from the prototype chain. You can check this using .hasOwnProperty(): (Of course if you do want to include inherited properties just remove the if statement).

Here is the general case:

for(var index in object) { 
   if (object.hasOwnProperty(index)) {
       var value = object[index];
       // do something with object value here.
   }
}

Here is the example case you mentioned where you want to create a duplicate object with the value of each key duplicated replicated according to the value of the var numberofobjects (i've added in two solutions whereby you either modify the existing object or create a new one):

// function to repeat value as a string inspired by disfated's answer here http://stackoverflow.com/questions/202605/repeat-string-javascript

function repeatValue(value, count) {
    value = String(value); // change to string to be able to add " > " as in question
    if (count < 1) return '';
    var result = '';
    while (count > 1) {
        if (count & 1) result +=  value + " > ";
        count >>= 1, value += " > " + value;
    }
    return result + value;
}

var numberofobjects = 3;
var newObject = {}; // for use if creating a duplicate object with the new values

for(var x in defaults) { 
   if (defaults.hasOwnProperty(x)) {
       //use this to replace existing values
       defaults[x] = repeatValue(defaults[x], numberofobjects);
       
       //or use this to create values in the new object
       newObject[x] = repeatValue(defaults[x], numberofobjects);
   }
}

Solution 6 - Javascript

In your code:

for(x in defaults){
   defaults.x = defaults.x + " > y";
}

You need to say defaults[x] instead of defaults.x.

x is a variable holding a string that is the key into the defaults object, and the bracket (array-style) syntax lets you use that variable to get the property. With the dot notation defaults.x is looking for a property actually called "x", the equivalent of defaults["x"].

Solution 7 - Javascript

var yourVariable = {
  Bobe: 23,
  Pope: 33,
  Doop: 43,
  Dope: 53
};

for(var keyName in yourVariable){
 document.write(keyName, " : ",yourVariable[keyName]," ");
};

Solution 8 - Javascript

Taken from Mozilla:

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.values(object1));
// expected output: Array ["somestring", 42, false]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAaronView Question on Stackoverflow
Solution 1 - JavascriptPetahView Answer on Stackoverflow
Solution 2 - JavascriptBlair AndersonView Answer on Stackoverflow
Solution 3 - JavascriptKristian RoebuckView Answer on Stackoverflow
Solution 4 - JavascriptDerek SoikeView Answer on Stackoverflow
Solution 5 - JavascriptDavidView Answer on Stackoverflow
Solution 6 - JavascriptnnnnnnView Answer on Stackoverflow
Solution 7 - JavascriptPrem GurusamyView Answer on Stackoverflow
Solution 8 - JavascriptsatnamView Answer on Stackoverflow