簡體   English   中英

如何從javascript中的json對象獲取參數名稱?

[英]how to get a parameter's name from a json object in javascript ?

我想以字符串形式獲取json對象的參數名稱

myObject = { "the name": "the value", "the other name": "the other value" } 

有沒有辦法獲得"the name""the other name"的結果?

在jQuery中:

var myObject = { "the name": "the value", "the other name": "the other value" };
var indexes = [];
$.each(myObject,function(index,value){
   indexes.push(index);
});

console.log(indexes[0]) -> the name
console.log(indexes[1]) -> the other name

在純js中:

var myObject = { "the name": "the value", "the other name": "the other value" };
var indexes = [];
for(var index in myObject){
    indexes.push(index);
}

console.log(indexes[0]) -> the name
console.log(indexes[1]) -> the other name

在上面,您可以隨時中斷。 如果需要所有索引,則有一種更快的方法將它們放入數組中:

var myObject = { "the name": "the value", "the other name": "the other value" };
var indexes = Object.keys(myObject);

console.log(indexes[0]) -> the name
console.log(indexes[1]) -> the other name

當然。 您可以使用for-in循環獲取對象的屬性名稱。

for ( var prop in myObject ){
   console.log("Property name is: " + prop + " and value is " + myObject[prop]);
}

在此處獲取更多信息

我不確定您要完成什么,但是您可以使用Object.keys(object)輕松獲得對象的鍵

Object.keys(myObject)

這將為您提供對象鍵的數組,您可以使用其進行任何操作。

大多數現代瀏覽器都會允許您使用Object.keys方法從JSON對象獲取鍵列表(這就是您要查找的字符串)。 因此,您可以簡單地使用

var keys = Object.keys(myJsonObject);

獲取鍵的數組並根據需要使用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM