1

I need to restructure my data so that it fits in with another piece of code. I need to convert my data (which is a name,value pair) into the following structure so that that it is processed correctly. Using JQuery how would I do so?

{items: [
{value: "21", name: "Mick Jagger"},
{value: "43", name: "Johnny Storm"},
{value: "46", name: "Richard Hatch"},
{value: "54", name: "Kelly Slater"},
{value: "55", name: "Rudy Hamilton"},
{value: "79", name: "Michael Jordan"}
]};

Right now I've got a $.each loop which is feeding each name,value pair in but I don't know how I'd get that exact structure.

1
  • 9
    What exactly is your original structure? Commented Nov 7, 2011 at 15:38

1 Answer 1

7

Why use jQuery? Do it with javascript.

The following assumes your source is an object named values with properties, as opposed to an array with numeric indices:

var output = { items: [] };

for (key in values) {
  if (values.hasOwnProperty(key)) {
    output.items.push({ value : values[key], name: key });
  }
}
Sign up to request clarification or add additional context in comments.

13 Comments

Note that you shouldn't ever use for( in ) to iterate over arrays, as it will include all properties of the array object! Use a normal for-loop instead.
@x3ro From the answer - "The following assumes your source is an object"
Please use Object.keys instead of for ... in && hasOwnProperty
@jbabey: Yeah, it is just worth mentioning that, because it is not that obvious and I often see people doing it.
@Raynos If you intend to support most browsers, don't use Object.keys.
|

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.