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

动态从嵌套对象数组提取ID并转换为对象数组的实现问询

Solution

Absolutely, this is totally achievable with JavaScript's map and reduce methods. Here's how you can do it:

var originalArr = [ 
  [ { ID: 3, name: 'Beef' }, { ID: 4, name: 'Macaroni' }, { ID: 5, name: 'Sauce#1' } ], 
  [ { ID: 1, name: 'Lettuce' }, { ID: 2, name: 'Brocoli' } ] 
];

var output = originalArr.map(innerArray => 
  innerArray.reduce((accumulator, currentItem) => {
    // Use the item's ID as the key, assign the entire object as the value
    accumulator[currentItem.ID] = currentItem;
    return accumulator;
  }, {}) // Start with an empty object for each inner array
);

console.log(output);

How it works:

  • map: Iterates over each inner array in your original array, transforming each one into a new structure.
  • reduce: For each inner array, builds a new object by accumulating each item. We start with an empty object ({}), then for every item in the inner array, we add a property to the accumulator where the key is the item's ID (automatically converted to a string, which matches your desired output) and the value is the original object.

Result:

The output variable will be exactly what you're looking for:

[
  {
    '3': { ID: 3, name: 'Beef' },
    '4': { ID: 4, name: 'Macaroni' },
    '5': { ID: 5, name: 'Sauce#1' }
  },
  {
    '1': { ID: 1, name: 'Lettuce' },
    '2': { ID: 2, name: 'Brocoli' }
  }
]

If you have duplicate IDs in any inner array, note that the last occurrence will overwrite the previous ones—this is standard object behavior in JS. If you need to handle duplicates differently, feel free to ask for adjustments!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:16:42