Let's suppose you have the following array of objects:
const users = [
{ id: 0, name: 'John' },
{ id: 1, name: 'Wayne' },
{ id: 2, name: 'David' },
];
From this array of objects, if you wish to extract the values of all object properties called "name
" for example into a new array, you can do so in the following ways:
Using Array.prototype.map()
You can use the Array.prototype.map()
method to create a new array consisting of only specific key's values. Using Array.prototype.map()
would call the provided callback function for each element of the array and add the returned values to the new resulting array. For example:
// ES5+
const names = users.map(function (user) {
return user.name;
});
console.log(names); // ['John', 'Wayne', 'David']
In ES6+, you can shorten this syntax by using the arrow function and unpacking the relevant object property passed to the provided callback function, for example, like so:
// ES6+
const names = users.map(({ name }) => name);
console.log(names); // ['John', 'Wayne', 'David']
Using a for
Loop
If you're unable to support a minimum ES5, then you may simply iterate over the array using a for
loop for example, and extract object values into a new array in the following way:
const names = [];
for (let i = 0; i < users.length; i++) {
if (!users[i].hasOwnProperty('name')) {
continue;
}
names.push(users[i].name);
}
console.log(names); // ['John', 'Wayne', 'David']
Please note the use of the Object.prototype.hasOwnProperty()
method in the code above; it is used so that object's inherited properties can be skipped and only object's own properties are considered.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.