【问题标题】:Convert an array of object to the array of string in TypeScript [duplicate]将对象数组转换为 TypeScript 中的字符串数组 [重复]
【发布时间】:2018-01-03 13:30:26
【问题描述】:

使用 lodash 我需要将对象数组转换为字符串数组。

原始数组,

const tags = [{
    "display": "tag1",
    "value": "tag1"
}, {
    "display": "tag2",
    "value": "tag2"
}]

预期结果,

const tags = ["tag1", "tag2"]

我试过这样,

const data = [{
    "display": "tag1",
    "value": "tag1"
}, {
    "display": "tag2",
    "value": "tag2"
}]

    const result = _(data)
        .flatMap(_.values)
        .map((item) => { if (typeof item === 'string') { return item; } else { return; } })
        .value()
        console.log('result', result);

【问题讨论】:

  • 你尝试了什么?另外,普通的 JS 也可以,不需要使用 lodash。

标签: javascript arrays lodash


【解决方案1】:

你不需要lodash,你可以用map来做普通的JS

DEMO

const tags = [{
    "display": "tag1",
    "value": "tag1"
}, {
    "display": "tag2",
    "value": "tag2"
}]

var result = tags.map(a => a.display);
console.log(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    相关资源
    最近更新 更多