我试图将当前的JSON结构转换为另一个结构时遇到问题
var data = [
{
"url": "asset/01.flv",
"pic": "asset/01.jpg"
},
{
"url": "asset/02.flv",
"pic": "asset/02.jpg"
},
{
"url": "asset/03.flv",
"pic": "asset/03.jpg"
},
{
"url": "asset/04.flv|asset/05.flv|asset/06.flv|asset/07.flv|asset/08.flv",
"pic": "asset/04.jpg|asset/05.jpg|asset/06.jpg|asset/07.jpg|asset/08.jpg"
},
{
"url": "asset/09.flv|asset/10.flv",
"pic": "asset/09.jpg|asset/10.jpg"
}
]
我想将数据转换为这样的输出结构.
这是我想要实现的结果的目标.
var data = [
{
"url": "asset/01.flv",
"pic": "asset/01.jpg"
},
{
"url": "asset/02.flv",
"pic": "asset/02.jpg"
},
{
"url": "asset/03.flv",
"pic": "asset/03.jpg"
},
{
"url": "asset/04.flv",
"pic": "asset/04.jpg"
},
{
"url": "asset/05.flv",
"pic": "asset/05.jpg"
},
{
"url": "asset/06.flv",
"pic": "asset/06.jpg"
},
{
"url": "asset/07.flv",
"pic": "asset/07.jpg"
},
{
"url": "asset/08.flv",
"pic": "asset/08.jpg"
},
{
"url": "asset/09.flv",
"pic": "asset/09.jpg"
},
{
"url": "asset/10.flv",
"pic": "asset/10.jpg"
}
]
对我来说很困难,有人可以在这件事情上帮助我吗?我试了几个小时.使用lodash或下划线或普通JS是可以的.提前致谢.
解决方法:
你可以使用Array#reduce来做到这一点.我们的想法是遍历数组并检查url和pic是否有|他们的价值观.
如果是,则拆分值并将所有项目推送到结果.如果没有,请按原样推送网址和图片.
var data = [{"url":"asset/01.flv","pic":"asset/01.jpg"},{"url":"asset/02.flv","pic":"asset/02.jpg"},{"url":"asset/03.flv","pic":"asset/03.jpg"},{"url":"asset/04.flv|asset/05.flv|asset/06.flv|asset/07.flv|asset/08.flv","pic":"asset/04.jpg|asset/05.jpg|asset/06.jpg|asset/07.jpg|asset/08.jpg"},{"url":"asset/09.flv|asset/10.flv","pic":"asset/09.jpg|asset/10.jpg"}];
var result = data.reduce((r, {url, pic}) => {
if (url.includes('|') && pic.includes('|')) {
var urls = url.split('|');
var pics = pic.split('|');
urls.forEach((u, i) => {
r.push({url: u, pic: pics[i]});
});
} else {
r.push({url, pic})
}
return r;
}, []);
console.log(result);