Suppose you have an array of objects, each with the same property name, for example:
const users = [
{ id: 1, name: 'Tom', age: 18 },
{ id: 2, name: 'Jerry', age: 21 },
{ id: 3, name: 'Alice', age: 25 }
];
The attribute values need to name
be extracted and stored in a new array. Use map()
methods and arrow functions to achieve this requirement
const names = users.map(user => user.name);
console.log(names); // 输出:['Tom', 'Jerry', 'Alice']
Finally, we can encapsulate the tool class to extract the dynamic attribute names in the dynamic array
function arrAttr(arr, key) {
return arr.map(obj => obj[key]);
}
const ages = arrAttr(users, 'age');
console.log(ages); // 输出:[18, 21, 25]