Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a specific property from array of objects angular

I have a array of objects, for e.g. like one below.

[{ "foo" : "a", "bar" : "x", baz: 1},
{ "foo" : "b", "bar" : "y", baz: 2},
{ "foo" : "c", "bar" : "z", baz: 3}]

Now I want to select only foo property from this array to another array like

["a","b","c"]

I can do this using looping and adding each property to another array as

var fooArray =[];
angular.forEach(arrayName, function (value, key) {
    fooArray.push(value.foo);               
});

But is is possible just as we do in c# linq select statement without us looping into the array like

var fooArray = arrayName.Select(m => m.foo) // c# way

Is there any elegant way without us looping?

like image 876
Chaitanya Gadkari Avatar asked Aug 13 '15 05:08

Chaitanya Gadkari


People also ask

How do you access data from an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };

How do you find the value of an array?

get() is an inbuilt method in Java and is used to return the element at a given index from the specified Array. Parameters : This method accepts two mandatory parameters: array: The object array whose index is to be returned.


1 Answers

You can use map function like below. It is modern browser's script I mean it will perfectly work in IE8+ versions. It will not work in IE8 older versions.

As per doc

The map() method creates a new array with the results of calling a provided function on every element in this array.

AND

Calls a defined callback function on each element of an array, and returns an array that contains the results.

var result = arrayName.map(function(a) {return a.foo;});
like image 129
Vineet Avatar answered Sep 28 '22 09:09

Vineet