Return 某个对象的值基于在数组中找到具有另一个值的对象
Return a certain Object's value based on finding the Object in the array with another value
使用的技术:js、jquery、angular 和下划线。我有一组对象 0-4。每个对象都有 2 个值对 "num: it's value" 和 "text : it's value"。所以...
var arr = [
{
num: '1',
text: 'First Place'
},
{
num: '2',
text: 'Second place'
},
...
];
现在我有了所选对象的编号,但我需要切换到文本。
这是有效的 - "object 0 | num : 1" 已选择将 1 存储在变量 (selectedNum) 中。我如何根据 selectedNum 编码找到具有 1 和 return 文本的对象到变量 selectedText.
首选答案使用 underscore.js。
findWhere 会做:
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;
更新:
您也可以使用查找(参见 fiddle)。
终于明白了 - http://jsfiddle.net/gJPHw/262/
我仍然希望使用 ._find 解决它,但这可行。
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);
使用的技术:js、jquery、angular 和下划线。我有一组对象 0-4。每个对象都有 2 个值对 "num: it's value" 和 "text : it's value"。所以...
var arr = [
{
num: '1',
text: 'First Place'
},
{
num: '2',
text: 'Second place'
},
...
];
现在我有了所选对象的编号,但我需要切换到文本。
这是有效的 - "object 0 | num : 1" 已选择将 1 存储在变量 (selectedNum) 中。我如何根据 selectedNum 编码找到具有 1 和 return 文本的对象到变量 selectedText.
首选答案使用 underscore.js。
findWhere 会做:
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;
更新:
您也可以使用查找(参见 fiddle)。
终于明白了 - http://jsfiddle.net/gJPHw/262/
我仍然希望使用 ._find 解决它,但这可行。
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);