在javascript中访问对象数组中的字段值 [英] accessing field value in array of objects in javascript

查看:202
本文介绍了在javascript中访问对象数组中的字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"}]

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

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?

我尝试过 possibleOptions [option.cdOpzione] ,但是它不起作用,有没有办法做到这一点?我知道我想念一些东西.

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.

当前$.每个代码:

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

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

推荐答案

以通用方式,您无法避免额外的循环.不过,根据您的具体情况,可能会有一些特殊的解决方案.

In a generic way, you can't avoid the extra cycle. There may be particular solutions though, depending on your circumstances.

解决方案1 ​​

如果您重组数据,可以避免使用,使其成为一个以cdOption中的值作为键的对象以及一个具有描述和类型的值作为对象的对象.

You could avoid it if you restructure your data, to have possibleOptions be an object with the values in cdOption as keys and an object with description and type as value.

示例:

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然后减去一个.

Another thing you could do if the cdOption is always of the form OPT-index- where -index- is 1+ the index in the array is to parse the value you're looking for, extract the -index-, parseInt and subtract one.

示例:

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

演示: http://jsbin.com/opojozE/1/edit

这篇关于在javascript中访问对象数组中的字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆