最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Iterate over Object Literal Values - Stack Overflow

programmeradmin5浏览0评论

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

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";
}
Share Improve this question edited Apr 8, 2020 at 23:47 Makyen 33.3k12 gold badges92 silver badges125 bronze badges asked Feb 20, 2012 at 0:36 AaronAaron 2,5001 gold badge29 silver badges56 bronze badges
Add a comment  | 

8 Answers 8

Reset to default 118
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

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

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

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

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"].

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

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

Taken from Mozilla:

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

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

评论列表(0)

  1. 暂无评论