如何用TypeScript及Lodash将对象数组转换为字符串数组?
Hey there! Let's fix this up for you—your current approach is a bit overcomplicated and ends up giving duplicate values because you're flattening all property values from each object. Here's how to get the clean result you want with Lodash:
Simplest Solution
Since each object in your array has identical display and value properties, you can directly extract either one using _.map with a property path:
const data = [{ "display": "tag1", "value": "tag1" }, { "display": "tag2", "value": "tag2" }]; const result = _.map(data, 'value'); // Or use 'display'—both work here console.log(result); // Output: ["tag1", "tag2"]
_.map is perfect here because it iterates over the array and plucks the specified property from each object, which is exactly what you need.
Why Your Original Code Didn't Work
Your current code uses flatMap(_.values), which takes every value from each object (so each tag gets duplicated once, since each object has two string values). Then your map function just returns those strings, resulting in ["tag1", "tag1", "tag2", "tag2"]—not the unique array you want. The conditional check for strings is also unnecessary here, since all property values in your input are already strings.
Bonus: Handle Duplicates (If Needed)
If there's a chance your array might have duplicate tag values (even from different objects), you can add _.uniq to ensure you only get unique strings:
const result = _.uniq(_.map(data, 'value'));
内容的提问来源于stack exchange,提问作者abhijeetwebdev

