javascript - 如何从数组创建对象?
问题描述
我想使用循环从具有许多元素的数组中创建 json 对象
我怎样才能从这个数组中返回这个对象?
我的数组:
[
"text 1",
"text 2",
"text 3"
]
我要返回的对象:
return [
{
json: {
message: "text 1"
}
},
{
json: {
message: "text 2"
}
},
{
json: {
message: "text 3"
}
}
]
解决方案
您可以使用Array.map完成此操作
const input = [
"text 1",
"text 2",
"text 3"
];
const output = input.map((item) => ({
json: {
message: item
}
}));
console.log(output);