从数组中获取和匹配值

时间:2013-07-06 13:07:33

标签: javascript arrays

我有一个这样的数组:

var Data=[{
    "Class":"item1","element":["a","b","c","d","e"],
    "Class":"item2","element":["a","b","c","d","e"],
    "Class":"item3","element":["a","b","c","d","e"],
    "Class":"item4","element":["a","b","c","d","e"]
}];

我有两个变量:

var class='item1';
var element='a';

我想要一个条件,如果var类值与“item1”匹配,则var元素值应仅与其元素匹配,如:

if(class == Data.Class)then元素应该与它附近的Data.element匹配

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

这应该是您的数据......

var Data= [
    { "Class":"item1","element":["a","b","c","d","e"] },
    { "Class":"item2","element":["a","b","c","d","e"] },
    { "Class":"item3","element":["a","b","c","d","e"] },
    { "Class":"item4","element":["a","b","c","d","e"] },
];

然后你可以迭代它并找到你的价值。喜欢这个

var class='item1';
var element='a';
for(var i = 0; i < Data.length; ++i){
    if (Data[i].Class == class){
        for( var j = 0; j < Data[i].element.length; ++j){
            if ( Data[i].elements[j] == element){
               // do whatever
            }
        }
    }
}

答案 1 :(得分:0)

首先,您需要修复data

var Data= [
    { "Class":"item1","element":["a","b","c","d","e"] },
    { "Class":"item2","element":["a","b","c","d","e"] },
    { "Class":"item3","element":["a","b","c","d","e"] },
    { "Class":"item4","element":["a","b","c","d","e"] },
];

现在它是一个对象数组。

然后您可以查看该数组,例如使用for循环

var myclass = "item3"; // class is a reserved word
for (var i=0; i<Data.length;i++) {
    if (Data[i].Class == myclass) {
        // do something with that its data Data[i].element
    }
}