
对于前端程序员来说,我基本上每天都要与对象数组打交道。无论是从API接口获取数据、管理组件状态,还是进行复杂的数据转换,对象数组都是JavaScript中最核心的数据结构之一。今天给大家分享10个日常开发实用的对象数组操作示例,每个示例都提供完整可运行的代码和详细说明,希望对大家有所帮助!
// 使用场景:初始化数据、从API接收数据、动态生成测试数据
const users = [
{ id: 1, name: '小明', age: 20 },
{ id: 2, name: '小红', age: 22 },
{ id: 3, name: '小强', age: 25 }
];
// 动态创建示例:根据用户输入或配置生成数据
const newUsers = Array.from({ length: 3 }, (_, i) => ({
id: i + 1,
name: `用户${i + 1}`,
age: 20 + i
}));
console.log('静态创建的用户:', users);
console.log('动态创建的用户:', newUsers);
说明:静态创建适合固定数据,动态创建适合根据条件生成数据。Array.from方法特别适合生成序列化数据。
// 使用场景:渲染列表、统计数据、批量处理
const products = [
{ name: '手机', price: 1999, stock: 10 },
{ name: '电脑', price: 6999, stock: 5 },
{ name: '平板', price: 2999, stock: 8 }
];
// 场景1:控制台输出商品信息(调试或日志)
console.log('=== 商品信息 ===');
products.forEach(item => {
console.log(`${item.name}: ¥${item.price}`);
});
// 场景2:检查库存状态(业务逻辑处理)
console.log('\n=== 库存检查 ===');
for (const product of products) {
const status = product.stock < 6 ? '库存不足' : '库存充足';
console.log(`${product.name}: ${product.stock}件 (${status})`);
}
说明:forEach适合简单遍历,for...of比较适合需要中断或复杂逻辑的场景。
// 使用场景:搜索过滤、状态筛选、条件查询
const orders = [
{ id: 1, amount: 100, status: 'completed' },
{ id: 2, amount: 200, status: 'pending' },
{ id: 3, amount: 150, status: 'completed' },
{ id: 4, amount: 300, status: 'cancelled' }
];
// 场景1:显示特定状态的订单(如已完成订单页面)
const completedOrders = orders.filter(order => order.status === 'completed');
console.log('已完成的订单:', completedOrders);
// 场景2:查找符合条件的单个订单(如订单详情查询)
const bigOrder = orders.find(order => order.amount > 150);
console.log('金额大于150的第一个订单:', bigOrder);
// 场景3:检查是否存在特定订单(如权限验证)
const hasPending = orders.some(order => order.status === 'pending');
console.log('是否存在待处理订单:', hasPending);说明:filter返回所有匹配项,find只返回第一个匹配项,some用于验证存在性。

// 使用场景:数据格式化、提取特定字段、添加计算属性
const students = [
{ name: '张三', score: 85 },
{ name: '李四', score: 92 },
{ name: '王五', score: 78 }
];
// 场景1:提取学生姓名列表(用于选择器下拉框)
const names = students.map(student => student.name);
console.log('学生姓名列表:', names);
// 场景2:添加是否及格字段(计算衍生数据)
const withPass = students.map(student => ({
...student,
isPass: student.score >= 60,
grade: student.score >= 90 ? '优秀' : student.score >= 80 ? '良好' : '一般'
}));
console.log('包含成绩等级的学生:', withPass);
// 场景3:转换为其他格式(如API参数转换)
const apiParams = students.map((student, index) => ({
student_id: index + 1,
student_name: student.name,
exam_score: student.score
}));
console.log('API参数格式:', apiParams);
说明:map方法创建新数组而不修改原数据,非常适合数据转换场景。
// 使用场景:表格排序、价格筛选、时间线显示
const books = [
{ title: 'JavaScript', price: 59, publishYear: 2020 },
{ title: 'Python', price: 49, publishYear: 2019 },
{ title: 'Java', price: 69, publishYear: 2021 },
{ title: 'C++', price: 55, publishYear: 2018 }
];
// 场景1:价格从低到高排序(商品列表)
const sortedByPrice = [...books].sort((a, b) => a.price - b.price);
console.log('按价格升序:', sortedByPrice);
// 场景2:按书名排序(字母顺序)
const sortedByTitle = [...books].sort((a, b) =>
a.title.localeCompare(b.title)
);
console.log('按书名排序:', sortedByTitle);
// 场景3:按出版年份降序(最新优先)
const sortedByYear = [...books].sort((a, b) => b.publishYear - a.publishYear);
console.log('按年份降序:', sortedByYear);
说明:使用[...books]创建副本避免修改原数组,使用localeCompare正确比较中文字符。
// 使用场景:销售报表、成绩统计、数据分析
const sales = [
{ month: '1月', amount: 10000, profit: 3000 },
{ month: '2月', amount: 15000, profit: 4500 },
{ month: '3月', amount: 8000, profit: 2400 },
{ month: '4月', amount: 12000, profit: 3600 }
];
// 场景1:计算总销售额(财务报表)
const totalAmount = sales.reduce((sum, sale) => sum + sale.amount, 0);
console.log(`总销售额: ¥${totalAmount}`);
// 场景2:计算平均销售额
const averageAmount = totalAmount / sales.length;
console.log(`平均销售额: ¥${averageAmount.toFixed(2)}`);
// 场景3:查找最高和最低销售额
const highestSale = sales.reduce((max, sale) =>
sale.amount > max.amount ? sale : max, sales[0]
);
const lowestSale = sales.reduce((min, sale) =>
sale.amount < min.amount ? sale : min, sales[0]
);
console.log(`最高销售额: ${highestSale.month} - ¥${highestSale.amount}`);
console.log(`最低销售额: ${lowestSale.month} - ¥${lowestSale.amount}`);
说明:reduce是强大的聚合工具,比较适合各种统计计算,对于报表统计页面还是使用非常频繁的。
// 使用场景:清理重复数据、获取唯一值列表、数据去重
const items = [
{ id: 1, name: '苹果', category: '水果' },
{ id: 2, name: '香蕉', category: '水果' },
{ id: 1, name: '苹果', category: '水果' }, // 重复
{ id: 3, name: '橙子', category: '水果' },
{ id: 4, name: '土豆', category: '蔬菜' },
{ id: 2, name: '香蕉', category: '水果' } // 重复
];
// 场景1:基于id去重(主键去重)
const uniqueById = items.filter((item, index, self) =>
index === self.findIndex(i => i.id === item.id)
);
console.log('基于id去重:', uniqueById);
// 场景2:获取所有分类(获取唯一值)
const categories = [...new Set(items.map(item => item.category))];
console.log('所有分类:', categories);
// 场景3:按分类去重(保留每个分类的第一个)
const uniqueByCategory = items.filter((item, index, self) =>
index === self.findIndex(i => i.category === item.category)
);
console.log('按分类去重:', uniqueByCategory);
说明:对象去重需要基于特定字段属性,Set适合简单值去重。
// 使用场景:数据拼接、分页加载、多源数据整合
const arr1 = [
{ id: 1, name: 'A', type: 'type1' },
{ id: 2, name: 'B', type: 'type1' }
];
const arr2 = [
{ id: 3, name: 'C', type: 'type2' },
{ id: 4, name: 'D', type: 'type2' }
];
const arr3 = [
{ id: 5, name: 'E', type: 'type3' }
];
// 场景1:简单合并(数据拼接)
const merged = [...arr1, ...arr2];
console.log('合并arr1和arr2:', merged);
// 场景2:分页数据合并(加载更多)
const allData = [...arr1, ...arr2, ...arr3];
console.log('合并所有数据:', allData);
// 场景3:合并并添加来源标记
const mergedWithSource = [
...arr1.map(item => ({ ...item, source: 'arr1' })),
...arr2.map(item => ({ ...item, source: 'arr2' }))
];
console.log('带来源标记的合并:', mergedWithSource);
说明:扩展运算符...是最简洁的合并方式,可以减少很多代码量。
// 使用场景:编辑表单、状态更新、价格调整
let products = [
{ id: 1, name: '手机', price: 1999, discount: 0 },
{ id: 2, name: '电脑', price: 5999, discount: 0 },
{ id: 3, name: '耳机', price: 299, discount: 0 }
];
// 场景1:更新单个商品价格(编辑操作)
products = products.map(product =>
product.id === 2
? { ...product, price: 5499, updatedAt: new Date().toISOString() }
: product
);
console.log('更新电脑价格后:', products);
// 场景2:批量添加折扣(促销活动)
products = products.map(product => ({
...product,
discount: 0.1, // 10%折扣
finalPrice: product.price * 0.9
}));
console.log('添加折扣后:', products);
// 场景3:条件更新(清仓处理)
products = products.map(product => {
if (product.price < 1000) {
return { ...product, discount: 0.3, tag: '清仓特价' };
}
return product;
});
console.log('条件更新后:', products);
说明:使用map配合扩展运算符实现不可变更新,符合React等框架的最佳实践。
// 使用场景:列表分页、表格数据分页、无限滚动
const data = Array.from({ length: 25 }, (_, i) => ({
id: i + 1,
name: `项目${i + 1}`,
value: Math.random() * 100
}));
// 分页函数
function getPageData(data, page, pageSize) {
const start = (page - 1) * pageSize;
const end = start + pageSize;
const pageData = data.slice(start, end);
return {
data: pageData,
page,
pageSize,
total: data.length,
totalPages: Math.ceil(data.length / pageSize),
hasNext: end < data.length,
hasPrev: page > 1
};
}
// 场景1:获取第2页数据,每页5条
const page2 = getPageData(data, 2, 5);
console.log('第2页数据:', page2.data);
console.log('分页信息:', {
当前页: page2.page,
每页条数: page2.pageSize,
总条数: page2.total,
总页数: page2.totalPages,
是否有下一页: page2.hasNext
});
// 场景2:获取最后一页数据
const lastPage = getPageData(data, Math.ceil(data.length / 5), 5);
console.log('最后一页数据:', lastPage.data);
说明:分页是处理大量数据的必要手段,slice方法简单高效。
以上是前端中关于对象数组10个常用的用法,大家如果使用过程中遇到什么问题的话,欢迎沟通交流!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。