简体   繁体   中英

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

i would like to get the parameter name of a json object as a string

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

is there a way to get "the name" or "the other name" as a result ?

In 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

In pure 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

In above you could break whenever you would like. If you need all the indexes, there is faster way to put them in array:

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

Sure. You can use a for-in loop to get property names of the object.

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

More info on for-in here .

I'm not certain what you want to accomplish, but you can get the keys to the object pretty easily with Object.keys(object)

Object.keys(myObject)

That will give you an array of the object's keys, which you could do whatever you want with.

Most modern browsers will let you use the Object.keys method to get a list of keys (that's what the strings you are looking for are called) from a JSON object. So, you can simply use

var keys = Object.keys(myJsonObject);

to get an array of the keys and do with these as you wish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM