How to convert following multidimensional array to single dimensional associative array with minimum loop in jQuery?
array(array('a'=>3),array('b'=>2),array('c'=>4),array('d'=>3))
Expected result:
array('a'=>3,'b'=>2,'c'=>4,'d'=>3);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
…is the JS syntax you’re looking for in your result. JS doesn’t have associative arrays in the sense that, say, PHP does: it has objects, which do (approximately) the same job.
If the code you show is valid in some other language (PHP?), it could be converted to a JSON string and when the JSON is parsed by JS you’d end up with a JS array of objects as follows:
To convert that to a JS object rather than an array of objects the simplest way is probably to make use of
jQuery.extend():Demo: http://jsfiddle.net/SqcEw/
Note that if more than one of the elements in the original array had the same property name one would clobber the other in the final object.
Further reading:
$.extend()