我有一个我需要转换为JSON的String数组。
creators=["a","b","c","d"...."x"]
我想转换为以下JSON格式。
{
"creators":[
{"creator": "a"},
{"creator": "b"},
{"creator": "c"},
----------------,
{"creator": "x"}
]
}
我如何在Node中实现它?
答案 0 :(得分:0)
您可以使用Array.prototype.map
const creators=["a","b","c","d", "x"]
const object = {
creators: creators.map(creator => ({ creator }))
// ^^^ object property shorthand
// { creator: creator }
};
console.log(object); // or JSON.stringify(object) if you need JSON
如果创作者是一个数组,它可以正常工作,但有时候创作者才有 一个元素,我得到creators.map不是一个功能错误。
如果creators
并非总是数组,则可以执行以下操作:
creators = Array.isArray(creators) ? creators : [creators];
creators.map(creator => ({ creator }))
相当于:
creators.map(creator => {
return { creator: creator };
})
答案 1 :(得分:0)
试试这个
var c=["a","b","c","d","x"]
var obj = '{"creators":['
for (var i = 0; i < c.length; i++) {
obj += '{"creators" : "'+ c[i]+'"}'
if(i != c.length-1){
obj += ", ";
}
}
obj += "]}";
json = JSON.parse(obj)
console.log(json);