Javascript Javascript获取对象键名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10334267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:54:36  来源:igfitidea点击:

Javascript get object key name

javascript

提问by John Magnolia

How would I get the key name for the follow? E.g I want "button1" and "button2"?

我将如何获得关注的关键名称?例如我想要“button1”和“button2”?

var buttons = {
    button1: {
        text: 'Close',
        onclick: function(){

        }
    },
    button2: {
        text: 'Close2',
        onclick: function(){

        }
    }
}

var i;
for(i in buttons){
    if(buttons.hasOwnProperty(i)){
        alert(buttons[i].text);
    }
} 

I tried using .push()although this didn't work.

我尝试使用.push()虽然这不起作用。

回答by Sampson

This might be better understood if you modified the wording up a bit:

如果您稍微修改一下措辞,可能会更好地理解这一点:

var buttons = {
  foo: 'bar',
  fiz: 'buz'
};

for ( var property in buttons ) {
  console.log( property ); // Outputs: foo, fiz or fiz, foo
}

Note here that you're iterating over the properties of the object, using propertyas a reference to each during each subsequent cycle.

请注意,您正在迭代对象的属性,property在每个后续循环中用作对每个属性的引用。

MSDNsays of for ( variable in [object | array ] )the following:

MSDN 是这样说的for ( variable in [object | array ] )

Before each iteration of a loop, variable is assigned the next property name of object or the next element index of array. You can then use it in any of the statements inside the loop to reference the property of object or the element of array.

在循环的每次迭代之前,变量被分配对象的下一个属性名称或数组的下一个元素索引。然后,您可以在循环内的任何语句中使用它来引用对象的属性或数组的元素。

Note also that the property order of an object is not constant, and can change, unlike the index order of an array. That might come in handy.

另请注意,与数组的索引顺序不同,对象的属性顺序不是恒定的,并且可以更改。那可能会派上用场。

回答by jAndy

ECMAscript edition 5 also offers you the neat methods Object.keys()and Object.getOwnPropertyNames().

ECMAscript 第 5 版还为您提供了简洁的方法Object.keys()Object.getOwnPropertyNames().

So

所以

Object.keys( buttons );  // ['button1', 'button2'];

回答by Quentin

Change alert(buttons[i].text);to alert(i);

更改alert(buttons[i].text);alert(i);

回答by IProblemFactory

Variable iis your looking key name.

变量i是你看起来的关键名称。

回答by VXxed

Assuming that you have access to Prototype, this could work. I wrote this code for myself just a few minutes ago; I only needed a single key at a time, so this isn't time efficient for big lists of key:value pairs or for spitting out multiple key names.

假设您可以访问 Prototype,这可以工作。几分钟前我为自己写了这段代码;我一次只需要一个键,所以这对于键值对的大列表或吐出多个键名来说不是很省时。

function key(int) {
    var j = -1;
    for(var i in this) {
        j++;
        if(j==int) {
            return i;
        } else {
            continue;
        }
    }
}
Object.prototype.key = key;

This is numbered to work the same way that arrays do, to save headaches. In the case of your code:

这被编号为与数组相同的工作方式,以避免头痛。就您的代码而言:

buttons.key(0) // Should result in "button1"

回答by Akash Jain

Here is a simple example, it will help you to get object key name.

这是一个简单的示例,它将帮助您获取对象键名称。

var obj ={parts:{costPart:1000, salesPart: 2000}}; console.log(Object.keys(obj));

var obj ={parts:{costPart:1000, salesPart: 2000}}; console.log(Object.keys(obj));

the output would be parts.

输出将是部分

回答by Tim Pozza

An ES6 update... though both filter and map might need customization.

ES6 更新...虽然过滤器和地图都可能需要自定义。

Object.entries(theObj)returns a [[key, value],] array representation of an object that can be worked on using Javascript's array methods, .each(), .any(), .forEach(), .filter(), .map(), .reduce(), etc.

Object.entries(theObj)返回一个对象的 [[key, value],] 数组表示,可以使用 Javascript 的数组方法,.each(), .any(), .forEach(), .filter(), .map(), .reduce() 等

Saves a ton of work on iterating over parts of an object Object.keys(theObj), or Object.values()separately.

节省大量迭代对象部分Object.keys(theObj)Object.values()单独的工作。

const buttons = {
    button1: {
        text: 'Close',
        onclick: function(){

        }
    },
    button2: {
        text: 'OK',
        onclick: function(){

        }
    },
    button3: {
        text: 'Cancel',
        onclick: function(){

        }
    }
}

list = Object.entries(buttons)
    .filter(([key, value]) => `${key}`[value] !== 'undefined' ) //has options
    .map(([key, value], idx) => `{${idx} {${key}: ${value}}}`)
    
console.log(list)