简体   繁体   中英

Loop through an array of objects

I have an array of objects like this -

    [{"name":"admission[year]","value":"2011-12"},{"name":"admission[class]","value":"Nursery"}]

How can i access the name value pairs like admission[year] - 2011-12, and admission[class] - nursery in javascript.

var x = [{"name":"admission[year]","value":"2011-12"},{"name":"admission[class]","value":"Nursery"}]
var i, len = x.length;
for(i = 0; i < len; i++)
    console.log(x[i].name + ': ' + x[i].value);

Outputs:

admission[year]: 2011-12
admission[class]: Nursery

IE. x[0].name === "admission[year]" and x[1].value === "Nursery"

/*

using jquery you can do something like this 

*/

$.each( ['a','b','c'], function(key, value){
   alert( "Index #" + key + ": " + value );
 });
var arr = [{ "name": "admission[year]", "value": "2011-12" }, { "name": "admission[class]", "value": "Nursery"}];
for (element in arr) {
    var combinedValue = arr[element].name + ' ' + arr[element].value;
    alert(combinedValue);
}

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