我有这个带有这些JSON对象的数组。我想将KEY值转换为Javascript数组,因此它看起来像。看一下Artist键。
我该怎么做?
json_data = [
{
artist: "picaso",
cover: "http:/blah.jpg",
genre: "illouson",
title: "mypicture",
uploaddate: "2019-04-22T19:48:43.454Z",
url: "https://blah.com"
},
{
artist: "malevich",
cover: "http:/blah.jpg",
genre: "black square",
title: "mypicture",
uploaddate: "2019-04-22T19:48:43.454Z",
url: "https://blah.com/blacksquare"
},
]
>
预期输出
json_data = [
{
artist: ["picaso"],
cover: "http:/blah.jpg",
genre: "illouson",
title: "mypicture",
uploaddate: "2019-04-22T19:48:43.454Z",
url: "https://blah.com"
},
{
artist: ["malevich"],
cover: "http:/blah.jpg",
genre: "black square",
title: "mypicture",
uploaddate: "2019-04-22T19:48:43.454Z",
url: "https://blah.com/blacksquare"
},
]
答案 0 :(得分:0)
只需使用简单的forEach()
循环即可将artist
属性设置为Array
类型:
var json_data = [
{
artist: "picaso",
cover: "http:/blah.jpg",
genre: "illouson",
title: "mypicture",
uploaddate: "2019-04-22T19:48:43.454Z",
url: "https://blah.com"},
{
artist: "malevich",
cover: "http:/blah.jpg",
genre: "black square",
title: "mypicture",
uploaddate: "2019-04-22T19:48:43.454Z",
url: "https://blah.com/blacksquare"},
];
json_data.forEach((item) => item.artist? item.artist = [item.artist]: item.artist);
console.log(json_data);
答案 1 :(得分:0)
使用地图
json_data = [
{
artist: "picaso",
cover: "http:/blah.jpg",
genre: "illouson",
title: "mypicture",
uploaddate: "2019-04-22T19:48:43.454Z",
url: "https://blah.com"},
{
artist: "malevich",
cover: "http:/blah.jpg",
genre: "black square",
title: "mypicture",
uploaddate: "2019-04-22T19:48:43.454Z",
url: "https://blah.com/blacksquare"},
]
console.log(json_data.map(e=>e.artist=[e.artist]))
答案 2 :(得分:0)
只需使用map
:
const json_data = [{
artist: "picaso",
cover: "http:/blah.jpg",
genre: "illouson",
title: "mypicture",
uploaddate: "2019-04-22T19:48:43.454Z",
url: "https://blah.com"
},
{
artist: "malevich",
cover: "http:/blah.jpg",
genre: "black square",
title: "mypicture",
uploaddate: "2019-04-22T19:48:43.454Z",
url: "https://blah.com/blacksquare"
}
];
const res = json_data.map(obj => obj.artist ? { ...obj, artist: [obj.artist] } : obj);
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }