1

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 ?

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.