You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中修改JSON对象的quantity_available并回写文件

修改嵌套对象数组中的字段并写回JSON文件

核心逻辑

你已经拿到了解析后的products对象,里面包含fish、tank、plant三个数组,每个数组内的对象都有quantity_available字段。要批量修改这个字段,只需要先遍历这三个类别数组,再逐个处理数组内的产品对象——这就是你困惑的双层循环逻辑。

具体实现代码

1. 简洁写法(forEach嵌套)

这种写法代码更清爽,适合大多数场景:

const fs = require('fs');
const path = require('path');

// 你已完成的读取解析步骤
const filePath = path.join(__dirname, 'products.json');
const products = JSON.parse(fs.readFileSync(filePath, 'utf8'));

// 遍历所有类别数组(fish/tank/plant)
Object.values(products).forEach(category => {
  // 遍历当前类别下的每个产品对象
  category.forEach(product => {
    // 这里写你的修改逻辑,示例:库存加1
    product.quantity_available += 1;
    // 也可以设固定值:product.quantity_available = 15;
  });
});

// 按原格式写回文件,2代表缩进2个空格,保证格式一致
fs.writeFileSync(filePath, JSON.stringify(products, null, 2), 'utf8');

2. 传统for循环嵌套

如果更习惯用for循环,逻辑完全一致:

// 读取解析步骤同上...

// 获取所有类别数组的键名
const categoryKeys = Object.keys(products);
for (let i = 0; i < categoryKeys.length; i++) {
  const currentCategory = products[categoryKeys[i]];
  for (let j = 0; j < currentCategory.length; j++) {
    const product = currentCategory[j];
    // 示例:库存翻倍
    product.quantity_available *= 2;
  }
}

// 写回文件步骤同上...

关键细节

  • Object.values(products)直接提取出三个类别数组,不用重复写三次遍历逻辑
  • 写回文件时,JSON.stringify的第三个参数2用来指定缩进空格数,确保输出的JSON格式和原文件一致
  • 因为解析后的JSON对象是引用类型,直接修改对象属性就会同步到products变量中

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 10:35:26