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
arrayto be an array containing the values of the id and name, you can change this line:to
But I probably wouldn’t use an array for that, I’d probably just use an object:
Then you can access it like this:
In fact, does
arrayreally need to be an array at all? If not, just make it an object:Make
idthe key andnamethe value:And this is how you loop it:
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: