Extract list of values from an array of objects to an array based on a key in JavaScript.

There may be a situation where you want to extract the list of values of a specific key from an objects to an array. 



Method 1:

In one way, we can use both for loop and Array.push() method and achieve it. 

For example, we have an Array of objects as below

let studentsObject = [
    {
        "name": "John",
        "age": 26
    },
    {
        "name": "Helen",
        "age": 42
    },
    {
        "name": "Cole",
        "age": 54
    },
    {
        "name": "Noah",
        "age": 38
    }
]

we can extract the values as shown below 

let namesList;
studentsObject.forEach(student => {
    namesList.push(student.name)
});
console.log(namesList);

//Output
['John', 'Helen', 'Cole', 'Noah']

Method 2:

The simple and easy way is using map function as below

let namesList = studentsObject.map(student => student.name);
console.log(namesList);

//Output
['John', 'Helen', 'Cole', 'Noah']

Here we've to assign the map function to a variable. If we don't assign to a variable, then the whole array object will be printed as it is.

Comments

Popular posts from this blog

Avoiding multiple API calls in Angular by using shareReplay method of RxJS

How to improve the unit tests running time in Angular