最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the key value of a JSON object matching another given value? - Stack Overflow

programmeradmin0浏览0评论

i have this JSON:

var projects_array = new Array(
{name:"myName1", id:"myid1", index:1},
{name:"myName2", id:"myid2", index:2},
{name:"myName3", id:"myid3", index:3},  

);

I need to get the "index" value of the object matching an specific "id" value. So if my "id" is "myid1" y would get "1".

here is part of my code:

 var myid = $(this).attr('id'); //this is the id value

projects_array.map(function (proj) {
    if (proj.id == myid) {
        return proj   // returns Undefined  
    } 
   }); 

Finally, I need to assign that value in a variable to use it later, THANKS :)

i have this JSON:

var projects_array = new Array(
{name:"myName1", id:"myid1", index:1},
{name:"myName2", id:"myid2", index:2},
{name:"myName3", id:"myid3", index:3},  

);

I need to get the "index" value of the object matching an specific "id" value. So if my "id" is "myid1" y would get "1".

here is part of my code:

 var myid = $(this).attr('id'); //this is the id value

projects_array.map(function (proj) {
    if (proj.id == myid) {
        return proj   // returns Undefined  
    } 
   }); 

Finally, I need to assign that value in a variable to use it later, THANKS :)

Share Improve this question asked Apr 8, 2012 at 0:26 lilymzlilymz 3872 gold badges7 silver badges16 bronze badges 3
  • 2 Code tip: Never use new Array(). Instead, use array literals: [1, 2, 3] – Ry- Commented Apr 8, 2012 at 0:31
  • @minitech, I got this advise before from SO but why, can you give some idea ? – The Alpha Commented Apr 8, 2012 at 0:36
  • 1 @SheikhHeera: It's shorter, it's a little more efficient, it's standard, and people can replace Array to mean whatever they want it to mean. Plus, there's the fact that new Array(5) won't give you [5] but rather [,,,,]. – Ry- Commented Apr 8, 2012 at 0:39
Add a ment  | 

1 Answer 1

Reset to default 3

I think you're selecting the index successfully, but when you return the value, it goes into a new array ("maps" there if you will). Try something like this:

var myproj; 
var myindex;
projects_array.map(function (proj) {
    if (proj.id == myid) {
        myproj = proj;
        myindex = proj.index;
    } 
}); 
发布评论

评论列表(0)

  1. 暂无评论