如何将JavaScript对象中可变长度属性拼接为对象新属性
Got it, let's walk through how to solve this problem. You need to add a new property to each object in your myObject.myObject array, where this property is built by concatenating values from the variable-length parameters array. Here are a few flexible implementations depending on your exact needs:
Basic Implementation (Modify Original Object)
If you want to directly add the new property to the existing objects, use forEach to iterate through each item and process its parameters:
// Iterate over each object in the main array myObject.myObject.forEach(item => { // Option 1: Concatenate all "name" values into a comma-separated string item.concatenatedNames = item.parameters.map(param => param.name).join(', '); // Option 2: Concatenate all "special" values with a pipe separator item.concatenatedSpecials = item.parameters.map(param => param.special).join(' | '); // Option 3: Concatenate key-value pairs (e.g., "name1: xxx, name2: yyy") item.concatenatedPairs = item.parameters.map(param => `${param.name}: ${param.special}`).join(', '); });
How this works:
item.parameters.map(...)extracts the specific value (likenameorspecial) from each parameter object, turning the array of objects into an array of strings..join('separator')converts that array into a single string using your chosen separator (comma, pipe, etc.).- We assign this string to a new property on the original
item(e.g.,concatenatedNames).
Immutable Implementation (Return New Array)
If you don't want to modify the original objects and prefer a new array with the added properties, use map instead:
// Create a new array with updated objects (original objects remain unchanged) const updatedMyObject = { myObject: myObject.myObject.map(item => ({ ...item, // Copy all existing properties from the original item concatenatedNames: item.parameters.map(param => param.name).join(', '), concatenatedSpecials: item.parameters.map(param => param.special).join(' | ') })) };
Handle Edge Cases
What if an item has an empty parameters array? Add a fallback to avoid empty strings:
myObject.myObject.forEach(item => { item.concatenatedNames = item.parameters.length > 0 ? item.parameters.map(param => param.name).join(', ') : 'No parameters available'; });
You can adjust the separator, the fields you're concatenating, and the fallback text to match your exact use case!
内容的提问来源于stack exchange,提问作者Leo Messi

