简体   繁体   中英

how to create a multi dimensional array in javascript inside a jquery each loop?

I have this example:

var name;
var id;
var array = []; 

$.each(data, function(index, element) {
name = element.name;
id = element.id;
array[id] = name;
<a href="#" onClick="myFunction(array)">send</a>
console.log(array);
});

In this case .each will iterate 5 times and id will become 1, 2, 3, 4, 5 and name will change to five names

i would like to create a multidimensional array or an object that will look like this:

[1:name1] for the first iteration
[2:name2] for the second on
...

the pass each pair of values to the myFunction function and inside that function to have access to the array values:

function myFunction(array){ // alert the key and value }

Any ideas how can I accomplish this scenario?

It's not clear what you're trying to do, but if you want each entry in array to be an array containing the values of the id and name, you can change this line:

array[id] = name;

to

array[id] = new Array(id, name);

But I probably wouldn't use an array for that, I'd probably just use an object:

array[id] = {id: id, name: name};

Then you can access it like this:

x = array[id].name;

In fact, does array really need to be an array at all? If not, just make it an object:

data = {};

Make id the key and name the value:

data[id] = name;

And this is how you loop it:

function myFunction(data) {
    var id, name;

    for (id in data) {
        name = data[id];
        alert("id is " + id + ", name is " + name);
    }
}

With a plain object like that, there's no need, but if the object you're looping may have a prototype behind it, you'd want to only look at the object's own properties:

function myFunction(data) {
    var id, name;

    for (id in data) {
        if (data.hasOwnProperty(id)) {
            name = data[id];
            alert("id is " + id + ", name is " + name);
        }
    }
}

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