JavaScript对象数组操作求助:添加与修改数组内对象元素
操作嵌套数组的两个函数实现
首先修正你提供的数组语法(末尾多余的点已移除,补充逗号让结构更清晰):
const a = [ { name: 'A', car: [ { color: 'red', type: 'limbo' }, { color: 'blue', type: 'yamaha' } ] }, { name: 'B', car: [ { color: 'green', type: 'beam' } ] } ];
1. 给name='A'的对象添加新车
直接通过find()定位目标对象,再修改其car数组即可(适合普通场景,操作简单):
function addCarToA() { // 找到数组中第一个name为'A'的对象 const personA = a.find(item => item.name === 'A'); if (personA) { // 向car数组推入新车 personA.car.push({ color: 'black', type: 'mitsu' }); console.log('添加完成', a); } }
如果是需要不可变更新的场景(比如React状态管理),用map()生成新数组,避免直接修改原数据:
function addCarToAImmutable() { const updatedArr = a.map(item => { if (item.name === 'A') { // 复制原对象,替换car数组为原数组加新车 return { ...item, car: [...item.car, { color: 'black', type: 'mitsu' }] }; } // 其他对象直接返回原引用 return item; }); console.log('不可变更新后的数组', updatedArr); // 若原数组是let声明,可赋值:a = updatedArr; }
2. 修改name='B'且type='beam'的车辆
先定位到name='B'的对象,再在其car数组里找到目标车辆,修改属性:
function updateCarOfB() { const personB = a.find(item => item.name === 'B'); if (personB) { // 找到type为'beam'的车辆 const targetCar = personB.car.find(car => car.type === 'beam'); if (targetCar) { // 直接修改车辆属性 targetCar.color = 'black'; targetCar.type = 'mitsu'; console.log('修改完成', a); } } }
同样,不可变更新的写法:
function updateCarOfBImmutable() { const updatedArr = a.map(item => { if (item.name === 'B') { // 处理B的car数组,替换目标车辆 const updatedCars = item.car.map(car => { if (car.type === 'beam') { return { color: 'black', type: 'mitsu' }; } return car; }); return { ...item, car: updatedCars }; } return item; }); console.log('不可变更新后的数组', updatedArr); }
最后在HTML中绑定按钮:
<button onclick="addCarToA()">给A添加新车</button> <button onclick="updateCarOfB()">修改B的目标车辆</button>
内容的提问来源于stack exchange,提问作者Thắng Nguyễn Quang
相关产品推荐
相关产品推荐

