gpt4 book ai didi

javascript - 使用 Lodash 将字符串数组转换为对象数组

转载 作者:行者123 更新时间:2023-12-03 01:12:03 27 4
gpt4 key购买 nike

lodash 有没有一种简单的方法来实现这一点:

const sampleSource = [
"String 1",
"String 2",
]

得到这个:

[
{id: "String 1", text: "String 1"},
{id: "String 2", text: "String 2"},
]

我需要像这样格式化它以传递到第三方 react 组件中。我已经尝试过 .map 和 .zipObject 了一些,但没能做到正确。

我认为这样的事情应该有效:

_.chain(sampleSource).map(s => ({ id: s, text: s })).value()

但它给了我:

[
{
id: ["String 1", "String 2"],
text: ["String 1", "String 2"],
}
]

最佳答案

类似这样的事情。添加了链示例。

const sampleSource = [
"String 1",
"String 2",
]

let result = _.map(sampleSource, function(item) {
return {id: item, text: item};
});

console.log(result);

let result2 = _.chain(sampleSource).map(function(item) {
return {id: item, text: item};
});

console.log(result2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

关于javascript - 使用 Lodash 将字符串数组转换为对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52173308/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com