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

如何用JavaScript创建多属性对象数组及从两数组生成含name/shade的对象数组?

Combine Parallel Arrays into an Array of Objects in JavaScript

Got it, let's work through this problem. You have two parallel arrays (names and shades) and need to merge them into an array of objects with name and shade properties—exactly the output you specified. Here are a few clean, practical ways to do this:

1. Use Array.map() (Most Concise)

The map() method is perfect here because it iterates over one array while letting you access the corresponding index in the second array. It's the most idiomatic modern JavaScript approach:

const names = ["black","white","red","blue","yellow"];
const shades = ["dark","light","dark","dark","light"];

const colorObjects = names.map((name, index) => ({
  name: name,
  shade: shades[index]
}));

// Or use object property shorthand for brevity:
// const colorObjects = names.map((name, index) => ({ name, shade: shades[index] }));

console.log(colorObjects);
// Output: [{ "name": "black", "shade": "dark" }, ...your expected result]

How it works: For each element in names, we create a new object where the name property is the current element, and shade is pulled from the same index in the shades array.

2. Use Array.forEach() (More Explicit)

If you prefer a more explicit loop structure, forEach() gets the job done by building the array step-by-step:

const names = ["black","white","red","blue","yellow"];
const shades = ["dark","light","dark","dark","light"];
const colorObjects = [];

names.forEach((name, index) => {
  colorObjects.push({
    name: name,
    shade: shades[index]
  });
});

console.log(colorObjects);

How it works: We initialize an empty array, then loop through each name (and its index), pushing a new object into the array each time.

3. Traditional for Loop (Maximum Compatibility)

If you need to support older environments where modern array methods aren't available, a standard for loop is reliable:

const names = ["black","white","red","blue","yellow"];
const shades = ["dark","light","dark","dark","light"];
const colorObjects = [];

for (let i = 0; i < names.length; i++) {
  colorObjects.push({
    name: names[i],
    shade: shades[i]
  });
}

console.log(colorObjects);

Important Note:

Make sure both arrays are the same length! If one is longer than the other, you'll end up with undefined values for the missing properties. You can add a quick check upfront if needed:

if (names.length !== shades.length) {
  console.error("Arrays must be the same length!");
  // Handle the mismatch here
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:05:42