0

I'm trying to map 2d array:

var fkOptionList2d = [[3, 'Orange'],[5, 'Banana'],[6, 'Coconut']]

to an associative array:

var fkOptionList1d = [{id: 1, label: 'Orange'},{id: 2, label: 'Banana'},{id: 3, label: 'Coconut'}]

but I'm new to underscore.js and don't quite get it yet. Should it be something like:

fkTableArr1d = _.object(_.map(fkTableArr2d, function(item, id) {
   return [{"id: " + id,"label: " + item}]
}));

?

3
  • Have actually you tried running anything? Your final bit of code should give you something close Commented Oct 29, 2013 at 10:47
  • good to know :) but I get Unexpected identifier near return Commented Oct 29, 2013 at 10:48
  • It should be return [{ id: id, label: item }]; you don't need to construct the object as a string (it's not JSON) Commented Oct 29, 2013 at 10:49

1 Answer 1

1

As per my understanding you need to use

return [{
    "id " : id, "label " : item
}]

instead of

return [{"id: " + id,"label: " + item}]

You are returning invalid JSON from the function

Additionally you don't need _.object method

fkTableArr1d = _.map(fkTableArr2d, function(item, id) {
      return [{
        "id " : id, "label " : item
        }];
    });

DEMO

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

6 Comments

I've changed it, but console.log shows Object {[object Object]: undefined}
@OverdrivenFall, Can you create a fiddle
@OverdrivenFall, see demo jsfiddle.net/W67Zr/2. you don't need _.object method. I have also updated answer
it works, but label becomes an array, according to console.log(fkTableArr1d[0][0]); : Object {id : 0, label : Array[2]}, shouldn't it be a string? `
ok, I got it, from the 3 of function(list, iterator, context) I actually wanted list[0] which is ID and list[1] - name
|

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.