js 多层对象数组,修改内层的数据
时间: 2024-05-08 19:15:50 浏览: 55
json.zip_json c
假设有如下的多层对象数组:
```javascript
let data = [
{
id: 1,
name: 'John',
orders: [
{ id: 101, product: 'Apple', amount: 5 },
{ id: 102, product: 'Banana', amount: 10 }
]
},
{
id: 2,
name: 'Mary',
orders: [
{ id: 201, product: 'Orange', amount: 3 },
{ id: 202, product: 'Grape', amount: 7 }
]
}
];
```
如果想要修改 John 的第一个订单数量为 8,可以这样做:
```javascript
data[0].orders[0].amount = 8;
```
修改后的结果为:
```javascript
[
{
id: 1,
name: 'John',
orders: [
{ id: 101, product: 'Apple', amount: 8 },
{ id: 102, product: 'Banana', amount: 10 }
]
},
{
id: 2,
name: 'Mary',
orders: [
{ id: 201, product: 'Orange', amount: 3 },
{ id: 202, product: 'Grape', amount: 7 }
]
}
]
```
同理,如果想要修改 Mary 的第二个订单数量为 5,可以这样做:
```javascript
data[1].orders[1].amount = 5;
```
修改后的结果为:
```javascript
[
{
id: 1,
name: 'John',
orders: [
{ id: 101, product: 'Apple', amount: 8 },
{ id: 102, product: 'Banana', amount: 10 }
]
},
{
id: 2,
name: 'Mary',
orders: [
{ id: 201, product: 'Orange', amount: 3 },
{ id: 202, product: 'Grape', amount: 5 }
]
}
]
```
阅读全文