You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用TypeScript及Lodash将对象数组转换为字符串数组?

Convert Object Array to String Array with 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:59:57