javascript - 使用 javascript 循环对象并将结果放入数组

标签 javascript arrays object for-loop for-in-loop

我试图循环访问一个对象,将对象中的一些值放入一个新数组中。但我真的很难弄清楚该怎么做。

这是我的对象:

var vehicles = {
    list:{
        "transport":{ //<-- This is the values I want to put to an array
            name:"transport",
            pixelWidth:31,
            pixelHeight:30,
            pixelOffsetX:15,
            pixelOffsetY:15,
            radius:15,
            speed:15,
            sight:3,
            cost:400,
            hitPoints:100,
            turnSpeed:2,
            spriteImages:[
                {name:"stand",count:1,directions:8}         
            ],
        },
        "harvester":{ //<-- This is the values I want to put to an array
            name:"harvester",
            pixelWidth:21,
            pixelHeight:20,
            pixelOffsetX:10,
            pixelOffsetY:10,
            radius:10,
            speed:10,
            sight:3,
            cost:1600,
            hitPoints:50,
            turnSpeed:2,
            spriteImages:[
                {name:"stand",count:1,directions:8}         
            ],
        },
        "scout-tank":{ //<-- This is the values I want to put to an array
            name:"scout-tank",
            canAttack:true,
            canAttackLand:true,
            canAttackAir:false,
            weaponType:"bullet",
            pixelWidth:21,
            pixelHeight:21,
            pixelOffsetX:10,
            pixelOffsetY:10,
            radius:11,
            speed:20,
            sight:3,
            cost:500,
            hitPoints:50,
            turnSpeed:4,
            spriteImages:[
                {name:"stand",count:1,directions:8}         
            ],
        },
        "heavy-tank":{ //<-- This is the values I want to put to an array
            name:"heavy-tank",
            canAttack:true,
            canAttackLand:true,
            canAttackAir:false,
            weaponType:"cannon-ball",
            pixelWidth:30,
            pixelHeight:30,
            pixelOffsetX:15,
            pixelOffsetY:15,
            radius:13,
            speed:15,
            sight:4,
            cost:1200,
            hitPoints:50,
            turnSpeed:4,
            spriteImages:[
                {name:"stand",count:1,directions:8}         
            ],
        }                       
    }

阅读其他文章后,我感觉应该使用 for-in 循环。对我来说真正的挑战是从我的对象中获得正确的值(value)。我看过这个post尝试解决它。​​

我找到了一个看起来像这样的解决方案:

var arr = [];

for (var key in vehicles)
    {
        var obj = vehicle[key];
        for (var prop in obj)
            {
                if(obj.hasOwnProperty(prop))
                {
                    arr.push(prop);
                }
            }
    }

console.log(arr);

但我刚刚从控制台收到此消息:

Array[0]length: 0__proto__: Array[0]

我还有一个正在运行的 fiddle here

我们将非常感谢所有帮助。

最佳答案

如果您只想要vehicles.list中的那些:

var arr = Object.keys(vehicles.list);

var vehicles = {
  list:{
    "transport":{ //<-- This is the values I want to put to an array
      name:"transport",
      pixelWidth:31,
      pixelHeight:30,
      pixelOffsetX:15,
      pixelOffsetY:15,
      radius:15,
      speed:15,
      sight:3,
      cost:400,
      hitPoints:100,
      turnSpeed:2,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    },
    "harvester":{ //<-- This is the values I want to put to an array
      name:"harvester",
      pixelWidth:21,
      pixelHeight:20,
      pixelOffsetX:10,
      pixelOffsetY:10,
      radius:10,
      speed:10,
      sight:3,
      cost:1600,
      hitPoints:50,
      turnSpeed:2,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    },
    "scout-tank":{ //<-- This is the values I want to put to an array
      name:"scout-tank",
      canAttack:true,
      canAttackLand:true,
      canAttackAir:false,
      weaponType:"bullet",
      pixelWidth:21,
      pixelHeight:21,
      pixelOffsetX:10,
      pixelOffsetY:10,
      radius:11,
      speed:20,
      sight:3,
      cost:500,
      hitPoints:50,
      turnSpeed:4,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    },
    "heavy-tank":{ //<-- This is the values I want to put to an array
      name:"heavy-tank",
      canAttack:true,
      canAttackLand:true,
      canAttackAir:false,
      weaponType:"cannon-ball",
      pixelWidth:30,
      pixelHeight:30,
      pixelOffsetX:15,
      pixelOffsetY:15,
      radius:13,
      speed:15,
      sight:4,
      cost:1200,
      hitPoints:50,
      turnSpeed:4,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    }    
  }
};
var arr = Object.keys(vehicles.list);
snippet.log(arr.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

如果您想要 vehicles任何属性引用的对象的所有键,那么:

var arr = [];
Object.keys(vehicles).forEach(function(key) {
  arr.push.apply(arr, Object.keys(vehicles[key]));
});

这里的技巧是,我们可以使用 arr.push.apply(arr,/*the other array*/) 将整个条目数组推送到 arr 上。

var vehicles = {
  list:{
    "transport":{ //<-- This is the values I want to put to an array
      name:"transport",
      pixelWidth:31,
      pixelHeight:30,
      pixelOffsetX:15,
      pixelOffsetY:15,
      radius:15,
      speed:15,
      sight:3,
      cost:400,
      hitPoints:100,
      turnSpeed:2,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    },
    "harvester":{ //<-- This is the values I want to put to an array
      name:"harvester",
      pixelWidth:21,
      pixelHeight:20,
      pixelOffsetX:10,
      pixelOffsetY:10,
      radius:10,
      speed:10,
      sight:3,
      cost:1600,
      hitPoints:50,
      turnSpeed:2,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    },
    "scout-tank":{ //<-- This is the values I want to put to an array
      name:"scout-tank",
      canAttack:true,
      canAttackLand:true,
      canAttackAir:false,
      weaponType:"bullet",
      pixelWidth:21,
      pixelHeight:21,
      pixelOffsetX:10,
      pixelOffsetY:10,
      radius:11,
      speed:20,
      sight:3,
      cost:500,
      hitPoints:50,
      turnSpeed:4,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    },
    "heavy-tank":{ //<-- This is the values I want to put to an array
      name:"heavy-tank",
      canAttack:true,
      canAttackLand:true,
      canAttackAir:false,
      weaponType:"cannon-ball",
      pixelWidth:30,
      pixelHeight:30,
      pixelOffsetX:15,
      pixelOffsetY:15,
      radius:13,
      speed:15,
      sight:4,
      cost:1200,
      hitPoints:50,
      turnSpeed:4,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    }    
  },
  list2: {
    "new-key-for-list2":{
      }
  }
};
var arr = [];
Object.keys(vehicles).forEach(function(key) {
  arr.push.apply(arr, Object.keys(vehicles[key]));
});
snippet.log(arr.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

或者,如果你真的喜欢单行,你可以使用Array#reduce,但我认为清晰度会受到影响:

var arr = Object.keys(vehicles).reduce(function(a, key) {
  a.push.apply(a, Object.keys(vehicles[key]));
  return a;
}, []);

var vehicles = {
  list:{
    "transport":{ //<-- This is the values I want to put to an array
      name:"transport",
      pixelWidth:31,
      pixelHeight:30,
      pixelOffsetX:15,
      pixelOffsetY:15,
      radius:15,
      speed:15,
      sight:3,
      cost:400,
      hitPoints:100,
      turnSpeed:2,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    },
    "harvester":{ //<-- This is the values I want to put to an array
      name:"harvester",
      pixelWidth:21,
      pixelHeight:20,
      pixelOffsetX:10,
      pixelOffsetY:10,
      radius:10,
      speed:10,
      sight:3,
      cost:1600,
      hitPoints:50,
      turnSpeed:2,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    },
    "scout-tank":{ //<-- This is the values I want to put to an array
      name:"scout-tank",
      canAttack:true,
      canAttackLand:true,
      canAttackAir:false,
      weaponType:"bullet",
      pixelWidth:21,
      pixelHeight:21,
      pixelOffsetX:10,
      pixelOffsetY:10,
      radius:11,
      speed:20,
      sight:3,
      cost:500,
      hitPoints:50,
      turnSpeed:4,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    },
    "heavy-tank":{ //<-- This is the values I want to put to an array
      name:"heavy-tank",
      canAttack:true,
      canAttackLand:true,
      canAttackAir:false,
      weaponType:"cannon-ball",
      pixelWidth:30,
      pixelHeight:30,
      pixelOffsetX:15,
      pixelOffsetY:15,
      radius:13,
      speed:15,
      sight:4,
      cost:1200,
      hitPoints:50,
      turnSpeed:4,
      spriteImages:[
        {name:"stand",count:1,directions:8}         
      ],
    }    
  },
  list2: {
    "new-key-for-list2":{
      }
  }
};
var arr = Object.keys(vehicles).reduce(function(a, key) {
  a.push.apply(a, Object.keys(vehicles[key]));
  return a;
}, []);
snippet.log(arr.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<小时/>

请注意,Object.keysArray#forEach(以及 Array#reduce)均已在 ES5(2009 年左右)中添加,所以它们存在于所有现代浏览器中,但在 IE8 和其他类似的旧浏览器中缺失。不过,这三个都可以填充。

关于javascript - 使用 javascript 循环对象并将结果放入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27044618/

相关文章:

javascript - 我如何处理 api 的 javascript/clojurescript 包装器库?

javascript - 媒体查询调试

javascript - 创建函数的额外实例

c - 使用 "*[]"和 "[][]"和 "(*)[]"传递 2D 数组?

javascript - Array.push() 与对象

javascript - 查找接下来的 30 天 (javascript)

Java从多维数组中删除行

arrays - 如何: multidimensional arrays in vhdl

php - 从 stdClass 对象数组中获取数据

java - 当您在不指定对象类型的情况下创建 ArrayList 时,它会在您添加第一个对象时自动创建它吗?