You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何用JavaScript遍历JSON数组并为每个对象添加内容?已尝试for in/forEach未果

Solution to Adding a New Object to Each Element in a JSON Array

It sounds like you're hitting common pitfalls with array iteration in JavaScript. Let's break down why your previous attempts might have failed and walk through reliable ways to get the job done.

First, let's ground this with an example. Suppose your original array looks like this:

[
  {"id": 1, "name": "Item 1"},
  {"id": 2, "name": "Item 2"},
  {"id": 3, "name": "Item 3"}
]

And you want to add a new details object to each element, resulting in:

[
  {"id": 1, "name": "Item 1", "details": {"price": 10, "stock": 50}},
  {"id": 2, "name": "Item 2", "details": {"price": 20, "stock": 30}},
  {"id": 3, "name": "Item 3", "details": {"price": 15, "stock": 40}}
]

Why for key in data might have failed

The for...in loop is built for iterating over object properties, not array elements. When used on an array, it loops over all enumerable properties (including any custom properties added to the array, not just indices). Also, the key variable is a string (e.g., "0", "1") instead of a number, which can lead to unexpected behavior if you're not careful. If you did want to use it (though it's not recommended for arrays), you'd need to access elements correctly and filter out non-index properties:

for (const key in data) {
  if (data.hasOwnProperty(key)) { // Skip inherited properties
    const item = data[key];
    item.details = { price: 10, stock: 50 };
  }
}

Reliable Methods to Achieve Your Goal

1. Using forEach (Mutates Original Array)

forEach is specifically designed for array iteration. It's clean and straightforward if you don't mind modifying the original array:

// Assume your array is stored in the 'data' variable
data.forEach(item => {
  // Add your new object here—you can also generate values dynamically
  item.details = { 
    price: Math.floor(Math.random() * 20) + 10, // Random price 10-30
    stock: Math.floor(Math.random() * 50) + 10  // Random stock 10-60
  };
});

If this didn't work before, double-check that you're referencing item directly (not trying to modify the loop's index variable).

2. Using map (Returns a New Array, No Mutation)

If you want to keep the original array untouched, use map. It creates a new array by applying a function to each element:

const updatedData = data.map(item => {
  // Spread the original item's properties and add the new object
  return {
    ...item,
    details: { price: 10, stock: 50 }
  };
});

This is often preferred because it avoids side effects (mutating the original array).

3. Traditional for Loop (Full Control)

If you want explicit control over iteration, a traditional for loop works perfectly:

for (let i = 0; i < data.length; i++) {
  const currentItem = data[i];
  currentItem.details = { price: 10 + i*5, stock: 50 - i*10 };
}

This is great if you need to use the index (i) to generate dynamic values for the new object.

Key Takeaways

  • Avoid for...in for arrays unless you have a specific reason to use it.
  • Use forEach if you want to modify the original array.
  • Use map if you want a new array without changing the original.
  • Always ensure you're accessing the array element correctly (e.g., data[i] in a for loop, or item in forEach/map) before adding the new object.

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

火山引擎 最新活动