0

I have an array...

var dataFilesArray =  [
   {data1: argumentA, file1: argumentB},
   {data2: argumentA, file2: argumentB}
   ]

For each data/file pair in the array, I would like to pass both values as arguments to function useData.

$.each(dataFilesArray {
   function useData (argumentA, argumentB)
});

Next loop would be for data2/file2, and so on until end of array.

function useData (argumentA, argumentB)

Can $.each be used this way?

Using

var dataFilesArray = [
    {data1: "someurl.com", file1: "somefileName.jpg"},
]

1 Answer 1

2

It's nothing to do with $.each, it's just what you put in the callback you give it:

$.each(dataFilesArray, function(index, entry) {
    useData(entry.data, entry.file);
});

Note I used data and file above; you wouldn't want the property names in each object in your array to be different, so the array would be:

var dataFilesArray =  [
   {data: argumentA, file: argumentB},
   {data: argumentA, file: argumentB}
   ];

If they're really going to be data1/file1 for the first entry, data2/file2 for the next, etc., you can do that, but it's a very odd structure and it's delicate — if you change the contents of the array, you have to change all those names. But for completeness:

$.each(dataFilesArray, function(index, entry) {
    var num = index + 1;
    useData(entry["data" + num], entry["file" + num]);
});
Sign up to request clarification or add additional context in comments.

4 Comments

they're really part is just awesome.
I am getting a RESOURCE_NOT_FOUND error. The data is urls and filenames. The urls are good.
@Jotter: The above works, there must be an issue applying it to your code.
You're right. It works. But I see your point, having the numbered names is not a good idea. Since they are pairs and I want to iterate them as such.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.