1

How can I get both the key name and value of a JSON object using Angular's forEach method?

   var institute = {
      "courses": [],
      "user_type": 3,
      "institute_name": "sd",
      "tagline": "sd",
      "overview": "sd",
      "specialities": "sd",
      "image": "dsd(2).sql"
    };

The above is the JSON data I've in a variable institute I need to access both the name and value. I've tried this:

angular.forEach(data,function (key,value){
     //key returns 0,1,2,3
     //value returns courses,user_type etc 
     //i need like eg) fd.append(user_type,3);
});

3 Answers 3

2

You need to change your loop args to:

angular.forEach(data,function (value, key)

and then:

fd.append(key, value);

DEMO

Documetation for angular.forEach

Sign up to request clarification or add additional context in comments.

Comments

2

The syntax is angular.forEach(data, function(value, key) { ... }).

Check out the fiddle below.

http://jsfiddle.net/HB7LU/21318/

Comments

1

You can use Object.keys() to get all the names in your object, then loop over those:

angular.forEach(Object.keys(data), function(key) {
    fd.append(key, data[key]);
});

Comments

Your Answer

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