Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array of objects get single value [duplicate]

Lets say I have an array of objects:

var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}

Is there an array function that will allow me to get one property as an array, for example:

namesArray = employees.reduceToProperty('name'); // none existent function i made up!

// should return ["George","Edward","Christine","Sarah"]

I know how get the desired result with a loop, I am just hoping for an array function or combination of functions exist that can do this in one line.

like image 386
Michiel Avatar asked Apr 12 '14 20:04

Michiel


People also ask

Can array have duplicate values javaScript?

With ES6, we have a javascript Set object which stores only unique elements. A Set object can be created with array values by directly supplying the array to its constructor. If the array has duplicate values, then they will be removed by the Set. This means that the Set will only contain unique array elements.

Can array hold duplicate values?

The standard way to find duplicate elements from an array is by using the HashSet data structure. If you remember, Set abstract data type doesn't allow duplicates. You can take advantage of this property to filter duplicate elements.


1 Answers

var names = employees.map(function(i) {
  return i.name;
});

names is now an array containing the name-properties of the objects.

like image 150
phylax Avatar answered Oct 13 '22 01:10

phylax