How to select a specific field from javascript array

I have an array object in javascript. I would select a specific field from all lines of the object.

I have an object like

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

I would like to get the output of only names like ["a","b","c"] without a loop over the sample object.

How to select one or two fields using jlinq? or any other plugin?

Thank you very much.

+4
source share
4 answers

You have the wrong definition. Instead of having an object containing 3 arrays, you need 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 get all your names as per your example:

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

But, not looping, I'm not sure how you get any number of values ​​.... why are there no loops?

Just say that you are doing a loop, here is how you do it:

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

or using jQuery (which is still looping)

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

You can try the following:

 var sample = [{Name:"a", Age:1}, {Name:"b", Age:2}, {Name:"c", Age:3}]; var Names = sample.map(function(item){return item.Name;}); 
+4
source

This Javascript makes no sense. This is syntactically incorrect. I assume you meant:

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

Then you can use jQuery to do something like this:

 var names = $(sample).map(function(){ return this.Name; }); 

But actually all jQuery does is loop through an object for you. Writing your own loop would be (slightly) faster. There is no way to do this without a loop.

+1
source
 // assuming you mean: var sample = [ {Name:"a",Age:1}, {Name:"b",Age:2}, {Name:"c",Age:3} ] 

Well, your biggest problem is that no matter what happens, you will have to loop. Now jQuery will let you hide this behavior:

 var output = [] $.each( sample, function(i,e){ output.push( e.Name )} ); 

But in principle, this is the same as:

 for( var i = 0; i < sample.length; i++ ) { output.push( v.Name ) } 
0
source

All Articles