Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

Find all elements of particular object from object array using jquery or 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));

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.

EDIT

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  

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You were on the right track with jQuery.grep() but did not use it correctly.

What you can do is:

$.grep(courses, function(e) { return e.list[1].name == 'spa'; })

Or more generally:

function find(name) {
    return $.grep(courses, function(e) { return e.list[1].name == name; });
}

And it will return all the elements of the courses array that match the given name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...