抓取数组中对象的名称

时间:2018-01-31 00:35:22

标签: javascript arrays object

所以我有一个填充了对象的数组,确切地说是10个,都是个人名字。

var upgrades = [
tree = {price: 20, rate:0.5, owned:0},
irr = {price: 80, rate:1, owned:0},
press = {price: 150, rate:2, owned:0},
cracker = {price: 400, rate:7, owned:0},
gmo = {price: 1000, rate:10, owned:0},
shack = {price: 1500, rate:13, owned:0},
truck = {price: 2000, rate:14, owned:0},
factory = {price: 5000, rate:18, owned:0},
rr = {price: 9000, rate:25, owned:0},
mGadget = {price: 15000, rate:30, owned:0},
];

我希望能够获取对象的名称,并能够将其分配给字符串变量。

var x=upgrades[0].getObjName

理论上x现在应该等于' tree&#39 ;;如何在不向我的对象添加名为name的变量的情况下执行此操作?

2 个答案:

答案 0 :(得分:3)

使用当前代码,您将创建全局变量,而不是数组中对象的键。首先,您需要修复语法,以便实际拥有一个对象数组。它应该是这样的:

var upgrades = [
  { tree: {price: 20, rate:0.5, owned:0} },
  { irr: {price: 80, rate:1, owned:0} },
  { press: {price: 150, rate:2, owned:0} },
  { cracker: {price: 400, rate:7, owned:0} },
  { gmo: {price: 1000, rate:10, owned:0} },
  { shack: {price: 1500, rate:13, owned:0} },
  { truck: {price: 2000, rate:14, owned:0} },
  { factory: {price: 5000, rate:18, owned:0} },
  { rr: {price: 9000, rate:25, owned:0} },
  { mGadget: {price: 15000, rate:30, owned:0} },
];

之后,您可以使用Object.keys()获取对象的第一个(仅在此情况下)键:

var x = Object.keys(upgrades[0])[0];
console.log(x); // --> tree

答案 1 :(得分:2)

你的数组是错误的。数组元素应该没有标识符。它应该是这样的

var upgrades = [
 {price: 20, rate:0.5, owned:0},
 {price: 80, rate:1, owned:0},
 {price: 150, rate:2, owned:0},
 {price: 400, rate:7, owned:0}

];

因此,您无法按名称获取数组元素。您可以通过索引

获取它
var x = upgrades[0]

如果你想使用命名标识符来抓取元素,那么你需要使用object而不是array

var upgrades = {
    tree : {price: 20, rate:0.5, owned:0},
    irr : {price: 80, rate:1, owned:0},
    press : {price: 150, rate:2, owned:0},
    cracker : {price: 400, rate:7, owned:0}

}

var x = upgrades.tree

按数组中的标识符进行检查:

按照此示例按标识符获取数组元素。只需在名为identifier的升级数组中为对象添加属性,并搜索特定标识符

var upgrades = [
   {identifier : 'tree',price: 20, rate:0.5, owned:0},
   {identifier: 'tiger',price: 80, rate:1, owned:0}

];

var obj = upgrades.filter(function(elem,index){
   return elem.identifier == 'tree'
})

console.log(obj)