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

Node.js中如何将解析后JSON的ID分别赋值给独立变量?

Solution for Assigning Supreme Stock IDs to Individual Variables

Hey there! Let's fix this step by step. First, let's address why your original code didn't work, then go over the right ways to get those IDs into item1, item2, etc.

Why Your Original Code Failed

The products_and_categories property in Supreme's mobile_stock.json is an object (key-value pairs where keys are category names like "Jackets" or "Shirts"), not an array. That means using parse_json.products_and_categories[0] will return undefined—you can't index into an object with a number unless the keys are numeric.

Step 1: Correctly Extract All IDs into the ids Array

First, let's make sure you're properly collecting all product IDs into your ids array. Here's a working snippet with the request module:

const request = require('request');

request('http://www.supremenewyork.com/mobile_stock.json', (error, response, body) => {
  if (!error && response.statusCode === 200) {
    const parse_json = JSON.parse(body);
    const ids = [];

    // Iterate through each category's product list
    Object.values(parse_json.products_and_categories).forEach(categoryProducts => {
      // Push each product's ID into the ids array
      categoryProducts.forEach(product => {
        ids.push(product.id);
      });
    });

    // Now we have all IDs in the ids array—let's assign them to item variables
    assignIdsToVariables(ids);
  }
});

Step 2: Assign IDs to item1, item2, etc.

You have two main options here, depending on your needs:

Option 1: Manual Assignment (Best for Small, Fixed Counts)

If you know exactly how many IDs you expect, you can assign them directly:

function assignIdsToVariables(ids) {
  const item1 = ids[0];
  const item2 = ids[1];
  const item3 = ids[2];
  // ... add more variables as needed

  // Test the results
  console.log(item1, item2, item3);
}

Option 2: Dynamic Assignment (Better for Variable Counts)

If the number of IDs might change, using an object to store the item variables is cleaner than polluting the global scope. You can generate keys like item1, item2 dynamically:

function assignIdsToVariables(ids) {
  const items = {};
  
  ids.forEach((id, index) => {
    // Use template literals to create keys like "item1", "item2"
    items[`item${index + 1}`] = id;
  });

  // Access the variables like this:
  console.log(items.item1); // First product ID
  console.log(items.item2); // Second product ID
  console.log(items.item3); // Third product ID
}

If you absolutely need standalone global variables (not inside an object), you can assign to global in Node.js, but this is generally bad practice because it clutters the global scope:

// Not recommended, but functional
ids.forEach((id, index) => {
  global[`item${index + 1}`] = id;
});

// Access directly without an object
console.log(item1);

Final Tips

  • Always log parse_json to the console to verify the structure of the JSON response
  • Using an object to store your item variables is more maintainable than individual variables, especially if the number of IDs changes over time

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:45:18