动态从嵌套对象数组提取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'sID(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
相关产品推荐
相关产品推荐

