'How to select a particular field from javascript array

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 = {
[Name:"a",Age:1],
[Name:"b",Age:2],
[Name:"c",Age:3]
}

I would like to get an output of only Names as ["a","b","c"] without looping over sample object.

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

Thanks a lot.



Solution 1:[1]

You can try this:

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

Solution 2:[2]

That Javascript has no meaning. It is syntatically 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 in reality all jQuery is doing is looping through the object for you. Writing your own loop would be (insignificantly) faster. There is no way to do this without a loop.

Solution 3:[3]

let names = [];
this.dtoArray.forEach(arr => names.push(arr.name));

Solution 4:[4]

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

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

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

But fundamentally, that is the same thing as:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stéphan
Solution 2 Paul
Solution 3 M Komaei
Solution 4 cwallenpoole