在使用array.map
方法时,不能直接导出对象,因为array.map
方法返回的是一个新的数组,而不是一个单独的对象。但是,你可以通过使用其他方法或技巧来解决这个问题。以下是几种常用的解决方法:
使用array.reduce
方法:
const array = [{ name: 'John' }, { name: 'Jane' }];
const newObj = array.reduce((acc, curr) => {
acc[curr.name] = curr;
return acc;
}, {});
export default newObj;
使用对象字面量:
const array = [{ name: 'John' }, { name: 'Jane' }];
const newObj = {};
array.forEach(item => {
newObj[item.name] = item;
});
export default newObj;
使用ES6的解构赋值:
const array = [{ name: 'John' }, { name: 'Jane' }];
const newObj = {};
array.forEach(({ name, ...rest }) => {
newObj[name] = { name, ...rest };
});
export default newObj;
使用ES6的Object.fromEntries
方法:
const array = [{ name: 'John' }, { name: 'Jane' }];
const newObj = Object.fromEntries(array.map(item => [item.name, item]));
export default newObj;
无论使用哪种方法,都可以将新的对象导出并使用。请根据你的具体需求选择适合的方法。