Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  3] [ 2]  / answers: 1 / hits: 75520  / 13 Years ago, thu, december 1, 2011, 12:00:00

I have an array of elements that I would like to apply a mapping to to convert it into key value pairs on a single object (to mimic an associative array).



The approach in Can destructuring assignment be used to effect a projection in CoffeeScript? does not seem to work for me as it results in a simple array instead of key/value pairs.



My language of choice is CoffeeScript or JavaScript.



An example:



[{name: 'a', value: 'b', other: 'c'}, {name: 'd', value: 'e', other: 'f'}]


is supposed to be transformed into:



{
a: 'b',
d: 'e'
}


One-liners are preferred. ;-)


More From » jquery

 Answers
2

To fix the syntax error, you'll have to expand { @name: @value } to:



o = {}; o[@name] = @value; o


You can then merge the objects with $.extend() and a splat (with the empty object to avoid accidentally extending jQuery):



$.extend {}, $(row).children('input').map(() -> o = {}; o[@name] = @value; o)...


Though, a simpler option would be just to use a 2-liner:



result = {}
$(row).children('input').each(() -> result[@name] = @value)

[#88798] Wednesday, November 30, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anabellejaynav

Total Points: 176
Total Questions: 105
Total Answers: 105

Location: Croatia
Member since Fri, Sep 11, 2020
4 Years ago
;