问题描述
我在JavaScript中有一个json-object,我想在其中获取使用过的密钥。我的JavaScript代码如下所示:
I have a json-object in JavaScript and I want to get the used keys in it. My JavaScript-Code looks like this:
var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];
我想要一个提醒我'人'和'年龄'的循环,这是关键json-Array中的第一个对象。
And I want a loop that alerts me 'person' and 'age', which are the keys of the first object in the json-Array.
推荐答案
[你所拥有的只是一个对象,而不是json-object 。 是一种文本符号。您引用的是使用和(又名对象文字语法)。]
[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]
如果您可以依赖ECMAScript5功能,可以使用用于获取对象中键(属性名称)的数组。请注意,旧版浏览器不会拥有它。如果没有,这是你自己可以提供的那个之一:
If you can rely on having ECMAScript5 features available, you can use the Object.keys
function to get an array of the keys (property names) in an object. Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:
if (typeof Object.keys !== "function") {
(function() {
var hasOwn = Object.prototype.hasOwnProperty;
Object.keys = Object_keys;
function Object_keys(obj) {
var keys = [], name;
for (name in obj) {
if (hasOwn.call(obj, name)) {
keys.push(name);
}
}
return keys;
}
})();
}
使用()循环遍历对象拥有的所有属性名称,并使用检查该属性由对象直接拥有而不是被继承。
That uses a for..in
loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty
to check that the property is owned directly by the object rather than being inherited.
(我本可以在没有自执行功能的情况下完成它,但我更喜欢我的函数,并与IE兼容 [嗯,不用不小心]。所以自执行函数就在那里避免使用de claration创建一个全局符号。)
(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)
这篇关于在JavaScript中获取json-object的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!