Poppy
Poppy

Reputation: 3092

jQuery substring

I have a key value pair something like this. this response comes back from the service in API.

var str = { "key1":"value1",..}

I need to use something lik this

for(var value in str) {

//I need to get only the value here. Eg: value1,value2 etc
}

how to get only value1 from this array using jquery sub string?

Upvotes: 0

Views: 914

Answers (4)

Umesh Patil
Umesh Patil

Reputation: 10685

var str = { "key1":"value1","key2":"value2","key2":"value2"};

var keyItems,valItems;
for(key in str){
   keyItems.push(key);
   valItems.push(str[key]);
}

// keyItems is array of all keys
// valItems is array of all values.

Upvotes: 0

Pradeep Singh
Pradeep Singh

Reputation: 3634

var str = { "key1":"value1",..}



for(var val in str) {

  var strval = str[val];
}

Upvotes: 0

user684934
user684934

Reputation:

If the response comes back as a set of (key, value) pairs, then you cannot really select the "first" value, because JSON objects do not have an order to their fields (different parsers may and probably will return the values in different order). You must know which key you want to access.

Upvotes: 0

Sjoerd
Sjoerd

Reputation: 75578

You can loop through an object (= key/value store) like this:

for (var key in items) {
    var value = items[key];
    // do things with key and value
}

Upvotes: 2

Related Questions