0

I have a js object which looks like this:

            var detailsArray = [
                                 {a0 :1,
                                  b0 :'A'},
                                 {a1 :2,
                                  b1 :'B'},
                                 {a2 :3,
                                  b2 :'C'},
                                 {a3 :4,
                                  b3 :'D'}];

This is how the object is created from the server side. On the client side I want to retrieve the value of all 'a's and add them to an array. The problem is that the variable name is changing depending on the index number. I have tried using underscore.js to do something like this:

          var variableA = new Array();
          for(var i = 0;i<detailsArray.length;i++){
            var temp = 'a' + i;
            variableA[i] = _.pluck(detailsArray,temp);
          }              

But this does not work. Can anyone tell how to get the values??

4

4 回答 4

3

There is two ways for accessing properties of object in javascript : using the dot like you just done, or using the array syntax style.

var obj = {'a':5};

obj.a
obj['a']

So with your code, this would give this :

var variableA = new Array();
for(var i = 0;i<detailsArray.length;i++){
    variableA[i] = detailsArray[i]['a' + i];
}
于 2013-04-15T07:31:51.297 回答
1

With underscore, you could do:

_.reduce(_.map(detailsArray, function(o, i) {
    return o['a' + i];
}), function(a, b) {
    return a + b;
});

And with native JS in newer browsers:

detailsArray.map(function(o, i) {
    return o['a' + i];
}).reduce(function(a, b) {
    return a + b;
});
于 2013-04-15T07:35:38.780 回答
0

here's one possible implementation

var tmp = []; 
for (var i = 0; i < detailsArray.length; i++) { 
   var obj = detailsArray[i]; // current object at index
   for (var props in obj) { // iterate properties in current object
       if (props.charAt() == "a") { // if starts with a....
           tmp.push(obj[props]);  // add value to array
           break; // stop the property iteration and move to next object
        }
   } 
}
console.log(tmp); // [1,2,3,4]
于 2013-04-15T07:31:23.607 回答
0

You can also do it like that:

for (var i = 0; i < detailsArray.length; i++)
  alert(eval("detailsArray[" + i + "].a" + i));

The code I provide will alert all the values corresponding to as in the json array, but obviously you can do whatever you want with the values obtained.

Here I am counting that all the keys will be of the kind a smth, but I suppose this is a safe assumption.

于 2013-04-15T07:34:33.070 回答