1

I need to access an element with a certain field value for the cdOption field in this array of objects of type possibleOptions:

[Object { cdOption="OPT001", description="Description 1", type="STRING"}, 
Object { cdOption="OPT002", description="Description 2", type="STRING"},
Object { cdOption="OPT003", description="Description 3", type="STRING"}]

The field value I'm looking for is extracted from antoher object in an array and so I'm alreay in a $.each cycle. Can I avoid entering another cycle in order to loop the possibleOptions object and look for the specified field value?

I've tried with possibleOptions[option.cdOpzione] but it doesn't work, is there a way to do this? I know I'm missing something.

current $.each code:

$.each(oldOptions, function(key, option) {    
    $.each(possibleOptions, function(key, possibleOption) {

        if (option.cdOption === possibleOptions.cdOption) {
            console.log(option.cdOption);
            console.log(possibleOption.description);
        }
    });
});
4

2 回答 2

3

一般来说,您无法避免额外的循环。不过,根据您的具体情况,可能会有特定的解决方案。

解决方案 1

如果你重组你的数据,你可以避免它,让 possibleOptions 成为一个对象,其中 cdOption 中的值作为键,而对象的描述和类型作为值。

例子:

var possibleOptions = {
  'OPT001' : { description:"Description 1", type:"STRING" },
  'OPT002' : { description:"Description 2", type:"STRING" },
  'OPT003' : { description:"Description 3", type:"STRING" }
};

var val = 'OPT002';
console.log(possibleOptions[val]);

解决方案 2

如果 cdOption 始终采用 OPT-index- 形式,您可以做的另一件事是,其中 -index- 为 1+ 数组中的索引是解析您要查找的值,提取 -index-、parseInt 并减去一个.

例子:

var val = 'OPT002';
var index = parseInt(val.substring(3))-1;
console.log(possibleOptions[index]);

两者的演示:http: //jsbin.com/opojozE/1/edit

于 2013-10-04T14:36:10.480 回答
1

Array.filter可以返回匹配条件的元素数组。例如,如果你想用 找到一个(或多个)对象cdOption == "OPT002",你可以说:

 var matches = possibleOptions.filter(
    function( element ) {
      return ( "OPT002" == element.cdOption );
    }
 );

并将matches包含:

 [ 
   { cdOption="OPT002", description="Description 2", type="STRING"}
 ]

如果您只是在寻找一场比赛:

 var myOption = (matches.length > 0) ? matches[0] : null;

如果您需要支持缺少Array.filter.

于 2013-10-04T14:36:48.010 回答