How to select a particular field from javascript array

前端 未结 4 1610
小蘑菇
小蘑菇 2021-01-04 15:48

I have an array object in javascript. I would to select a particular field from all the rows of the object.

I have an object like

var sample = {
[Nam         


        
4条回答
  •  Happy的楠姐
    2021-01-04 16:07

    You've got your definition the wrong way round. Instead of having an object containing 3 arrays, you want an array of objects.

    like this:

    var sample = [{Name:"a",Age:1},
       {Name:"b",Age:2},
       {Name:"c",Age:3}];
    

    Then you can do:

    var name0 = sample[0].Name;
    var age0 = sample[0].Age;
    

    or to get all your names as per your example:

    var names = [sample[0].Name,sample[1].Name,sample[2].Name];
    

    But, without looping im not sure how you would get any number of values.... why no looping?

    Just say you do loop, here's how you would do it:

    var names = []
    for(x in sample)
       names.push(sample[x].Name);
    

    or with jQuery (which is still looping)

    sample= jQuery.map(sample, function(n, i){
      return n.Name;
    });
    

提交回复
热议问题