在不知道属性名称的情况下访问JavaScript的对象属性

在不知道属性名称的情况下访问JavaScript的对象属性

本文介绍了在不知道属性名称的情况下访问JavaScript的对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况

我有一个返回的JSON对象。以下是一个例子。此特定示例中的 who 可以更改为所需的任何属性名称。所以例如下次这将是 name 而不是

I have a JSON object which is returned. And Below is an example of one. The who in this particular example can change to whatever property name is required. So for example next time this will be name rather than who

 [{"who":"Arthur"},{"who":"Craig"},{"who":"Dan"},{"who":"Daniel"},{"who":"Frank"},{"who":"Ian"},{"who":"jamie"},{"who":"Jason"},{"who":"jaz"},{"who":"Liam"},{"who":"Paul"},{"who":"Shaun"},{"who":"Wayne"}]

问题

在我的JS中我需要能够引用该属性并访问其数据而不使用其名称,因为名称将始终不同。

In my JS I need to be able to refer to the property and access its data without using its name as the name will always be something different.

我尝试了什么

data.forEach(function(m){
    console.info(m); // Object { who="Craig"}
    console.info(m.who); // Craig, as expected
    console.info(m[0]); // now not sure who to get it if who changes to name
});


推荐答案

Object.keys(m )[0] 应返回对象中的第一个可枚举属性名称 m

Object.keys(m)[0] should return the first enumerable property name in the object m.

所以如果 m = {who:Arthur}; 那么 m [Object.keys(m)[0]] Arthur

或者: Object.values(m)[0] 。请参阅

这篇关于在不知道属性名称的情况下访问JavaScript的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:06