我需要在可能类型的对象数组中访问cdOption字段具有特定字段值的元素:

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


我要查找的字段值是从数组中的另一个对象中提取的,所以我在$ .each周期中欠缺。
我可以避免进入另一个循环来循环可能的对象并寻找指定的字段值吗?

我尝试过
possibleOptions[option.cdOpzione]但这不起作用,有办法吗?我知道我想念什么。

当前$ .each代码:

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

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

最佳答案

通常,您无法避免额外的周期。但是,根据您的具体情况,可能会有特定的解决方案。

解决方案1

如果重新构造数据,可以使它成为可能,而让opspectOptions是一个以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

关于javascript - 在javascript中访问对象数组中的字段值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19183659/

10-12 00:13
查看更多