如何将数组对象中的字符串转换为大写形式
Got it! Let's walk through how to convert all the name strings in your array of objects to uppercase in JavaScript. Here are a couple of solid approaches:
Convert Object Array Name Values to Uppercase
1. Use Array.map() (Non-Mutating, Recommended)
This is the cleanest and safest method because it creates a new array instead of modifying the original one—no unexpected side effects!
const originalArray = [ { name: 'Rahul Patel' }, { name: 'Karan Patel' }, { name: 'Shubham Tayal' }, { name: 'rahul patel' }, { name: 'Prakash shah' } ]; // Generate a new array with uppercase names const uppercasedArray = originalArray.map(person => ({ ...person, // Copy all existing properties from the original object name: person.name.toUpperCase() // Convert the name to uppercase })); console.log(uppercasedArray);
Breakdown:
Array.map()loops through every object in your array.- The spread operator (
...person) ensures we keep any other properties each object might have (not justname). String.toUpperCase()converts thenamestring to all uppercase characters.
2. Mutate the Original Array (Use Sparingly)
If you specifically need to modify the original array instead of creating a new one, you can use Array.forEach():
const originalArray = [ { name: 'Rahul Patel' }, { name: 'Karan Patel' }, { name: 'Shubham Tayal' }, { name: 'rahul patel' }, { name: 'Prakash shah' } ]; // Modify the original array directly originalArray.forEach(person => { person.name = person.name.toUpperCase(); }); console.log(originalArray);
Heads Up:
Mutating original data can cause bugs in larger applications, so only use this if you're sure you don't need the original lowercase values anymore.
Handle Edge Cases
If some objects might be missing the name property, add a quick check to avoid runtime errors:
const uppercasedArray = originalArray.map(person => ({ ...person, name: person.name ? person.name.toUpperCase() : person.name // Preserve undefined/missing names }));
内容的提问来源于stack exchange,提问作者DIVAN AFTAB
相关产品推荐
相关产品推荐

