Reputation: 14393
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 ?
Upvotes: 1
Views: 9364
Reputation: 4136
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.
Upvotes: 1
Reputation: 12036
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
Upvotes: 4
Reputation: 1708
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.
Upvotes: 1
Reputation: 7281
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]);
}
Upvotes: 1