0

How to assign object into an array within a loop?

My progress so far

item = [];

$.each(result, function(){
    //loop and assign array into an array
    //result is an object
    //result.a
    //result.b
});

Expected final result

item = [
    {'a': a},
    {'b': b },
    .....
]
7
  • 1
    What is in result, and how does that relate to what goes into item? Commented Jan 9, 2015 at 2:15
  • @Barmar result is an object. loop through it and assign every of its result.a and result.b into item array. Commented Jan 9, 2015 at 2:20
  • I'm not sure why you would want an array like that. If each object has a different property, how will you access them? Commented Jan 9, 2015 at 2:23
  • @Barmar result.a will returned the value of 'a', and can't that be inserted into item[{'a':result.a}] ? Commented Jan 9, 2015 at 2:24
  • I mean how will you know what property to use when accessing item[n]? How do you know it's item[0].a and item[1].b? Commented Jan 9, 2015 at 2:31

1 Answer 1

1
var item = [];

$.each(result, function(key, value) {
    var newobj = {};
    newobj[key] = value;
    item.push(newobj);
}
Sign up to request clarification or add additional context in comments.

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.