使用jquery或javascript从对象数组中查找特定对象的所有元素 [英] Find all elements of particular object from object array using jquery or javascript

查看:2208
本文介绍了使用jquery或javascript从对象数组中查找特定对象的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

courses = [{
  code: 'English',
  otherFields: '1',
  list: [{id:'1'},{name:'eng'}]
}, {
  code: 'Spanish',
  otherFields: '2',
  list: [{id:'2'},{name:'spa'}]
}, {
  code: 'German',
  otherFields: '3',
  list: [{id:'3'},{name:'ger'}]
}]

 var resultSet = $.grep(courses.list, function (e) {
 return e.code.indexOf('German') == 0;
});

console.log(JSON.stringify(resultSet));

我想要的是:基于'name'参数,我想要获取该特定对象中的所有内容.示例:当我通过name = spa时,我应该获得"id = 2,name = spa".使用上面的代码,我得到的结果是未定义的.

What I want is: based on 'name' parameter I want to get everything in that particular object. Example: when I pass name=spa I should get ' id=2, name=spa'. Using the above code I get the result as undefined.

我检查了这个问题,但是没有帮不上什么忙.请帮忙.

I check this question but it didn't help much. Please help.

编辑

对不起朋友,但我真的很困惑.下面是我可以在控制台中看到的代码(它来自服务器,所以我不知道它的实际结构).

Sorry friends but I'm really confused. Below is the code while I can see in console (Its coming from server so I don't know how it is actually structured).

result : {Object}
 course : {Object}
  name : English
  list : {Object}
   1 : {Object}
     attr1 : value1
     attr2 : value2
   3 : {Object}
     attr1 : value1
     attr2 : value2
  other : value-other
  id : 1
 course : {Object}
  name : Spanish
  list : {Object}
   1 : {Object}
     attr1 : value1
     attr2 : value2
   3 : {Object}
     attr1 : value1
     attr2 : value2
  other : value-other
  id : 2  

当我使用result.course.id时,我得到的是1.我想要的是根据特定的name(西班牙语或英语)在course中获取整个内容.我希望我现在已经清楚了.

When I'm using result.course.id I'm getting 1. What I want is to get the entire thing inside course based on particular name (Spanish or English). I hop I made myself clear now.

很抱歉给您带来不便.请帮忙.

Sorry for the inconvenience that you'd to face before. Please help.

推荐答案

我已经为您编写了一个函数.您可以通过以下方式简单地做到这一点:-

I have written a function for you. You can do it simply by:-

function FindCourse(code) {
        for (var i = 0; i < courses.length; i++) {

            if (courses[i].list[1].name === code) {
                alert(courses[i].code);
                alert(courses[i].otherFields);
                alert(courses[i].list[0].id);
                alert(courses[i].list[1].name);
            }
        }
    }

请参阅fiddle- http://jsfiddle.net/rMECV/4/

See fiddle-http://jsfiddle.net/rMECV/4/

这篇关于使用jquery或javascript从对象数组中查找特定对象的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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