0
var fkTableArr1d = new Array();

fkTableArr1d = _.map(fkTableArr2d, function(list, iterator, context) {          
      return { "id " : list[0], "label " : list[1] };
    });

fkTableArr1d becomes: [Object, Object, Object]

1 object is a Object {id : "5", label : "fuel"}

Now how I'm supposed to get ID of an element with label fuel?

Below one doesn't work:

console.log(fkTableArr1d['fuel']);
1
  • Overdriven Fall, you are using the value 'fuel' as the index instead of finding which array object has this value. Check my answer. Commented Oct 29, 2013 at 12:03

3 Answers 3

2

Looks like you are looking for findWhere():

Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

_.findWhere(fkTableArr1d, {label : "fuel"});

Demo: http://jsfiddle.net/38qUE/1/

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

3 Comments

it works, I had error in my array (I've created it by "id" : list[0], "label" : list[1] instead of id : list[0], label : list[1])
Using string literals (the ones with quotes) vs "raw" identifiers should make no difference here.
somehow it did, because with string literals it didn't recognize .id, .label
0
var id = 0;
if(fkTableArr1d.label = 'fuel') id = fkTableArr1d.id;

Fiddle

Comments

0

use any the following code snippets:

snippet1:

fkTableArr1d =[{id : "5", label : "fuel1"}, {id : "6", label : "fuel"}, {id : "4", label : "fuel2"}];
for(x in fkTableArr1d)
    if(fkTableArr1d[x].label == 'fuel')
        alert(fkTableArr1d[x]['id']);//syntax1 for accessing object member. alerts '6'.

fiddle1

snippet2:

fkTableArr1d =[{id : "5", label : "fuel1"}, {id : "6", label : "fuel"}, {id : "4", label : "fuel2"}];
for(x in fkTableArr1d)
    if(fkTableArr1d[x].label == 'fuel')
        alert(fkTableArr1d[x].id);//syntax2 for accessing object member. alerts '6'.

fiddle2

5 Comments

I get undefined when I try for(x in fkTableArr1d) console.log(fkTableArr1d[x].id); or fkTableArr1d[x]['id']
You need var before x. Right now you are defining it as global.
@OverdrivenFall Please check the fiddle I have given. Perfectly working in the fiddle.
@Pavlo, Please check the fiddle. var is needed only when to declare x locally. But there is no such restriction here.
@Pavlo I completely agree with you. But didnt think of it too much to demonstrate this.

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.