0

Tech being used: js, jquery, angular, and underscore. I have an array of Objects 0-4. Each object has 2 value pairs "num: it's value" and "text : it's value". So...

var arr = [
    {
        num: '1',
        text: 'First Place'
    },
    {
        num: '2',
        text: 'Second place'
    },
    ...
];

Now I have the have the num of the selected object, but I need to switch to the text.

This is working - "object 0 | num : 1" is selected store 1 in variable (selectedNum). How do I code based on selectedNum find the object that has 1 and return text of said object to variable selectedText.

Prefered answer using underscore.js.

3
  • In this case you would have to loop over the array of objects until you find an object with the matching num. underscore likely has a helper method that makes it easier, but behind the scenes that's all it's doing Commented Sep 16, 2015 at 18:16
  • "Prefered answer using underscore.js." Consider reading their documentation, since that's why it exists. Commented Sep 16, 2015 at 20:50
  • @squint I did look at their documentation... it didn't really give me any take aways. Commented Sep 16, 2015 at 21:00

2 Answers 2

2

findWhere will do it:

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

var selectedNum = 3;
var selectedText = _.findWhere(arr, { num: selectedNum }).text;

Update:

You can also use find (see fiddle).

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

Comments

0

Got it finally - http://jsfiddle.net/gJPHw/262/

I still would like to have it solved using ._find, but this works.

var arrayOfFun = [
    { name:"string 1", code:"1" },
    { name:"string 2", code:"2" }
];

var selectedKey = arrayOfFun.filter(function ( selectedKey ) {
    return selectedKey.code === '1';
})[0];

console.log(selectedKey.name);

1 Comment

See updated answer with fiddle demonstrating use of underscore's find.

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.