使用 Object.keys() 方法获取每个对象的所有键值对,并遍历它们。然后使用 Array.prototype.map() 方法返回每个对象中需要的值。
示例代码:
const arr = [ { name: 'John', age: 28, gender: 'male' }, { name: 'Jane', age: 32, occupation: 'doctor' }, { name: 'Bob', salary: 50000, company: 'Google' } ];
const desiredKeys = ['name', 'age', 'gender', 'occupation', 'salary', 'company'];
const result = arr.map(obj => { const newObj = {}; desiredKeys.forEach(key => { newObj[key] = obj[key]; }); return newObj; });
console.log(result); // [{ name: 'John', age: 28, gender: 'male' }, { name: 'Jane', age: 32, occupation: 'doctor' }, { name: 'Bob', salary: 50000, company: 'Google' }]
下一篇:遍历对象数组并对每个对象应用模板