JavaScript提取数组对象中的相同的属性名,并返回新的数组

假设有一个包含多个对象的数组,每个对象都具有相同的属性名,例如:

const users = [
  { id: 1, name: 'Tom', age: 18 },
  { id: 2, name: 'Jerry', age: 21 },
  { id: 3, name: 'Alice', age: 25 }
];

需要将其中的 name 属性值提取出来,并存放到一个新的数组中。使用 map() 方法和箭头函数实现该需求

const names = users.map(user => user.name);
console.log(names); // 输出:['Tom', 'Jerry', 'Alice']

最后我们可以封装工具类 提取动态数组中动态的属性名

function arrAttr(arr, key) {
  return arr.map(obj => obj[key]);
}
const ages = arrAttr(users, 'age');
console.log(ages); // 输出:[18, 21, 25]

猜你喜欢

转载自blog.csdn.net/weixin_44948981/article/details/130225194