如何在JavaScript中将对象数组重映射为对象的对象?
Solution for Dynamic Grouping of Object Properties
Got it, let's tackle this problem efficiently—since manual mapping isn't practical with 50+ entries, we need a dynamic approach that automatically groups numeric properties under their preceding string-based keys.
Here's a JavaScript implementation that does exactly what you need:
const sample = [{ name: "name", value1: 1, mean: 2, create: 10, age: "age", player1: 20, player2: 40, sample: "sample", player3: 30, player4: 100 }]; // Extract the target object from the sample array (adjust if you have multiple objects) const sourceObj = sample[0]; const groupedResult = {}; let activeGroupKey = null; // Loop through every key-value pair in the source object for (const [propKey, propValue] of Object.entries(sourceObj)) { // When we hit a string value, this becomes our new group key if (typeof propValue === 'string') { activeGroupKey = propValue; // Initialize an empty object for this group in the result groupedResult[activeGroupKey] = {}; } // If we have an active group and the value is a number, add it to the group else if (activeGroupKey && typeof propValue === 'number') { groupedResult[activeGroupKey][propKey] = propValue; } } console.log(groupedResult); // Output matches exactly what you need: // { name: { value1: 1, mean: 2, create: 10 }, age: { player1: 20, player2: 40 }, sample: { player3: 30, player4: 100 } }
How this works:
- We start by grabbing the object from your sample array (if you have multiple objects in the array, you can wrap this logic in a
forEachloop to process each one). - We keep track of the current "active group" using
activeGroupKey—this gets set whenever we encounter a string value in the source object. - For every numeric value we encounter, we add it to the currently active group's object in the result.
- This setup scales seamlessly no matter how many string groups or numeric properties you have—no manual mapping required.
内容的提问来源于stack exchange,提问作者ajbee
相关产品推荐
相关产品推荐

