1

When using jQuery's serializeArray() on my form I get an array that looks like this:

[{
  "name": "name",
  "value": "1_filename.jpg"
}, {
  "name": "caption",
  "value": "1_caption"
}, {
  "name": "name",
  "value": "2_filename.jpg"
}, {
  "name": "caption",
  "value": "2_caption"
}, {
  "name": "name",
  "value": "3_filename.jpg"
}, {
  "name": "caption",
  "value": "3_caption"
}, {
  "name": "name",
  "value": "4_filename.jpg"
}, {
  "name": "caption",
  "value": "4_caption"
}]

But the rest of my code expects something more like this:

[{
  "name": "1_filename.jpg",
  "caption": "1_caption"
}, {
  "name": "2_filename.jpg",
  "caption": "2_caption"
}, {
  "name": "3_filename.jpg",
  "caption": "3_caption"
}, {
  "name": "4_filename.jpg",
  "caption": "4_caption"
}]

I'm new to manipulating arrays and objects like this and I'm not sure if there is already a convention that's used to convert the first to something similar to the second example.

My first guess is to just iterate by 2 and push them to a new object. I've tried iterating by one and checking the names but I'm having some trouble making sure the name and captions stay together correctly.

1
  • How looks like the raw data before you call the serializeArray()? Commented Mar 31, 2016 at 20:50

2 Answers 2

1

You can achieve this with a single loop which iterates over every other element of the array:

var output = [];
for (var i = 0; i < input.length; i += 2) {
    output.push({ name: input[i].value, caption: input[i + 1].value });
}

Working example

This is obviously rigidly tied to the assumption that the order of objects will be nameN, captionN, nameN+1, captionN+1...

If this assumption is not correct, you would need to implement your own sort() logic to put the input data in to the right format before creating your new array.

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

1 Comment

Thanks for this! In the end I found this version easier to read.
1

Loop by two, build an object, set the name and value into the obj for the two indexes, and push object into the array

var arr = [{
  "name": "name",
  "value": "1_filename.jpg"
}, {
  "name": "caption",
  "value": "1_caption"
}, {
  "name": "name",
  "value": "2_filename.jpg"
}, {
  "name": "caption",
  "value": "2_caption"
}, {
  "name": "name",
  "value": "3_filename.jpg"
}, {
  "name": "caption",
  "value": "3_caption"
}, {
  "name": "name",
  "value": "4_filename.jpg"
}, {
  "name": "caption",
  "value": "4_caption"
}];

var out = [];
for(var i=0; i<arr.length; i+=2){
   var obj = {};
   obj[arr[i].name] = arr[i].value;
   obj[arr[i+1].name] = arr[i+1].value;
   out.push(obj);
}
console.log(out);

Comments

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.