Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 301
Kavitha K Gowd Avatar asked Aug 24 '11 08:08

Kavitha K Gowd


People also ask

How do you return a single value from an array?

Use the reduce method to return a single value from an array of values.

How do you search an array in JavaScript?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

How do you filter an array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


2 Answers

let names = [];
this.dtoArray.forEach(arr => names.push(arr.name));
like image 78
M Komaei Avatar answered Sep 21 '22 08:09

M Komaei


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;});
like image 30
Stéphan Avatar answered Sep 19 '22 08:09

Stéphan