如何将数组中的1、true转换为Yes,0、false转换为No?
Got it, let's fix this for you! The key here is to properly check each lc value and map it to "Yes" or "No" while preserving the rest of the object properties. Here are a couple of solid approaches that will get you the exact result you want:
Using Array.map() (Clean & Concise)
This is the most straightforward method for transforming arrays in JavaScript. We'll create a copy of each object, update the lc property, and return the new object:
const arr = [ {id: 1, name: 'Emp1', lc: 1}, {id: 2, name: 'Emp2', lc: 0}, {id: 3, name: 'Emp3', lc: true}, {id: 4, name: 'Emp4', lc: false}, ]; const newArr = arr.map(obj => { // Spread operator copies all original properties return { ...obj, // Ternary operator checks if value is truthy (1/true → Yes, 0/false → No) lc: obj.lc ? 'Yes' : 'No' }; }); console.log(newArr); // Output matches your expected newArr exactly!
Using for...of Loop (If You Prefer Iteration)
If you were trying a for loop and hitting issues, the problem was likely not creating a copy of the original object (or forgetting to push the updated object to the new array). Here's the correct implementation:
const arr = [ {id: 1, name: 'Emp1', lc: 1}, {id: 2, name: 'Emp2', lc: 0}, {id: 3, name: 'Emp3', lc: true}, {id: 4, name: 'Emp4', lc: false}, ]; const newArr = []; for (const obj of arr) { // Create a copy of the object to avoid mutating the original const updatedObj = { ...obj, lc: obj.lc ? 'Yes' : 'No' }; newArr.push(updatedObj); } console.log(newArr);
Optional: Strict Value Matching (For Edge Cases)
If you want to ensure only exactly 1 or true map to "Yes" (and ignore other truthy values like strings or numbers greater than 1), you can use an explicit check:
lc: [1, true].includes(obj.lc) ? 'Yes' : 'No'
This way, values like 2 or "true" won't accidentally get converted to "Yes" if they ever end up in your data.
Both methods will produce the exact newArr you're expecting. The most common mistakes here are:
- Accidentally mutating the original array's objects instead of creating copies
- Forgetting to return the updated object in the
map()callback - Using incorrect conditionals that don't properly cover all four value types (1, 0, true, false)
内容的提问来源于stack exchange,提问作者Yank

