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

Node.js中用for循环将对象数组转为指定结构对象的问题

Solution Using For Loops in Node.js

Here's how you can convert your input array to the desired structure using nested for loops:

First, let's define your input data:

const input = [
  { "Material": "113/133", "Name": [ { "name": "WELD1", "value": 27520 }, { "name": "WELD2", "value": 676992 }, { "name": "WELD3", "value": 421 } ] },
  { "Material": "150/300", "Name": [ { "name": "WELD1", "value": 1441 }, { "name": "WELD2", "value": 555 }, { "name": "WELD3", "value": 100992 } ] }
];

Then, implement the conversion with for loops:

// Initialize the result object with empty arrays
const result = {
  Material: [],
  datasets: []
};

// Step 1: Collect all Material values
for (const item of input) {
  result.Material.push(item.Material);
}

// Step 2: Collect all unique WELD labels
const labelSet = new Set();
for (const item of input) {
  for (const nameObj of item.Name) {
    labelSet.add(nameObj.name);
  }
}
const labels = Array.from(labelSet);

// Step 3: Build datasets for each label
for (const label of labels) {
  const dataset = {
    label: label,
    data: []
  };
  
  // For each material, find the corresponding value for the current label
  for (const item of input) {
    let value = 0; // Default to 0 if label isn't found for this material
    for (const nameObj of item.Name) {
      if (nameObj.name === label) {
        value = nameObj.value;
        break; // Exit loop once we find the matching label
      }
    }
    dataset.data.push(value);
  }
  
  result.datasets.push(dataset);
}

console.log(result);

Output:

{
  Material: ["113/133", "150/300"],
  datasets: [
    { label: "WELD1", data: [27520, 1441] },
    { label: "WELD2", data: [676992, 555] },
    { label: "WELD3", data: [421, 100992] }
  ]
}

Notes:

  • I noticed your sample output had [100,20,0] for WELD3's data, but that doesn't match the input values. The code above uses the actual values from your input (421 and 100992). If you intended different values, you can adjust the input or add logic to modify the values as needed.
  • This solution handles cases where a WELD label might be missing from a Material entry by defaulting to 0.
  • We use a Set to collect unique labels to avoid duplicate dataset entries.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:58:49