Javascript 获取对象的属性名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4260308/
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-23 11:38:04  来源:igfitidea点击:

Getting the object's property name

javascriptobjectproperties

提问by Olical

I was wondering if there was any way in JavaScript to loop through an object like so.

我想知道 JavaScript 中是否有任何方法可以循环遍历这样的对象。

for(var i in myObject) {
    // ...
}

But get the name of each property like this.

但是像这样获取每个属性的名称。

for(var i in myObject) {
    separateObj[myObject[i].name] = myObject[i];
}

I can't seem to find anything like it on Google. They say to pass the names of the variables with them but this is not an option for what I am trying to achieve.

我似乎无法在 Google 上找到类似的东西。他们说要与他们一起传递变量的名称,但这不是我想要实现的选择。

Thanks for any help you can offer.

谢谢你的尽心帮助。

采纳答案by Trann

Use Object.keys():

使用Object.keys():

var myObject = { a: 'c', b: 'a', c: 'b' };
var keyNames = Object.keys(myObject);
console.log(keyNames); // Outputs ["a","b","c"]

Object.keys()gives you an array of property names belonging to the input object.

Object.keys()为您提供属于输入对象的属性名称数组。

回答by Josiah Ruddell

iis the name.

i是名字。

for(var name in obj) {
    alert(name);
    var value = obj[name];
    alert(value);
}

So you could do:

所以你可以这样做:

seperateObj[i] = myObject[i];

回答by Juan Mendes

DisclaimerI misunderstood the question to be: "Can I know the property name that an object was attached to", but chose to leave the answer since some people may end up here while searching for that.

免责声明我误解了这个问题:“我可以知道一个对象所附加的属性名称吗”,但选择留下答案,因为有些人可能会在搜索时到这里。



No, an object could be attached to multiple properties, so it has no way of knowing its name.

不,一个对象可以附加到多个属性,因此它无法知道它的名称。

var obj = {a:1};
var a = {x: obj, y: obj}

What would obj's name be?

obj 的名字是什么?

Are you sure you don't just want the property name from the for loop?

您确定您不只是想要 for 循环中的属性名称吗?

for (var propName in obj) {
  console.log("Iterating through prop with name", propName, " its value is ", obj[propName])
}

回答by Akhil Aravind

you can easily iterate in objects

您可以轻松地迭代对象

eg: if the object is var a = {a:'apple', b:'ball', c:'cat', d:'doll', e:'elephant'};

例如:如果对象是 var a = {a:'apple', b:'ball', c:'cat', d:'doll', e:'elephant'};

Object.keys(a).forEach(key => {
   console.log(key) // returns the keys in an object
   console.log(a[key])  // returns the appropriate value 
})

回答by ZEE

for direct access a object property by position... generally usefull for property [0]... so it holds info about the further... or in node.js 'require.cache[0]' for the first loaded external module, etc. etc.

用于按位置直接访问对象属性...通常对属性 [0] 有用...因此它包含有关进一步...的信息...或在 node.js 'require.cache[0]' 中为第一个加载的外部模块等等等等。

Object.keys( myObject )[ 0 ]
Object.keys( myObject )[ 1 ]
...
Object.keys( myObject )[ n ]

回答by Nikhil Vats

Other than "Object.keys( obj )", we have very simple "for...in" loop - which loops over enumerable property names of an object.

除了“Object.keys(obj)”之外,我们还有非常简单的“for...in”循环——它遍历对象的可枚举属性名称。

const obj = {"fName":"John","lName":"Doe"};

for (const key in obj) {
    //This will give key
      console.log(key);
    //This will give value
    console.log(obj[key]);
    
}

回答by Kevin Florida

To get the property of the object or the "array key" or "array index" depending on what your native language is..... Use the Object.keys() method.

要根据您的母语是什么来获取对象的属性或“数组键”或“数组索引”..... 使用 Object.keys() 方法。

Important, this is only compatible with "Modern browsers":

重要的是,这仅与“现代浏览器”兼容:

So if your object is called, myObject...

所以如果你的对象被调用,myObject...

var c = 0;
for(c in myObject) {
    console.log(Object.keys(myObject[c]));
}

Walla! This will definitely work in the latest firefox and ie11 and chrome...

瓦拉!这肯定适用于最新的 firefox 和 ie11 和 chrome ...

Here is some documentation at MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

这是 MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys 上的一些文档

回答by Combine

IN ES5

在 ES5

E.G. you have this kind of object:

EG 你有这样的对象:

var ELEMENTS = {
    STEP_ELEMENT: { ID: "0", imageName: "el_0.png" },
    GREEN_ELEMENT: { ID: "1", imageName: "el_1.png" },
    BLUE_ELEMENT: { ID: "2", imageName: "el_2.png" },
    ORANGE_ELEMENT: { ID: "3", imageName: "el_3.png" },
    PURPLE_ELEMENT: { ID: "4", imageName: "el_4.png" },
    YELLOW_ELEMENT: { ID: "5", imageName: "el_5.png" }
};

And now if you want to have a function that if you pass '0' as a param - to get 'STEP_ELEMENT', if '2' to get 'BLUE_ELEMENT' and so for

现在,如果你想要一个函数,如果你将“0”作为参数传递 - 得到“STEP_ELEMENT”,如果“2”得到“BLUE_ELEMENT”等等

function(elementId) {
    var element = null;

    Object.keys(ELEMENTS).forEach(function(key) {
        if(ELEMENTS[key].ID === elementId.toString()){
            element = key;
            return;
        }    
    });

    return element;
}

This is probably not the best solution to the problem but its good to give you an idea how to do it.

这可能不是问题的最佳解决方案,但它很好地为您提供了如何去做的想法。

Cheers.

干杯。

回答by Aaqib

As of 2018 , You can make use of Object.getOwnPropertyNames()as described in Developer Mozilla Documentation

截至 2018 年,您可以Object.getOwnPropertyNames()按照Developer Mozilla 文档中的说明使用

const object1 = {
  a: 1,
  b: 2,
  c: 3
};

console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]

回答by ekbgh

These solutions work too.

这些解决方案也有效。

// Solution One
function removeProperty(obj, prop) {
  var bool;
  var keys = Object.keys(obj);
  for (var i = 0; i < keys.length; i++) {
    if (keys[i] === prop) {
      delete obj[prop];
      bool = true;
    } 
  }
  return Boolean(bool);
}


//Solution two
function removeProperty(obj, prop) {
  var bool;
  if (obj.hasOwnProperty(prop)) {
      bool = true;
      delete obj[prop];
  }
  return Boolean(bool);
}