排序数组从多个源创建键值对



我有一个大的JSON数组,我想用它来创建键值对,将3个整数组合为一个对项目,将另一个整数组合作为第二个对项目。

我是一个程序员,所以一路上我都在寻找一些好的建议。该代码的目的是集成到我的自动化设置中。

我试图把showid,季节和情节作为一个组合整数,情节id和键值对。

因此,对于以下示例:

newarray=[{7.2.1:272,7.2.2:273}]

阵列中的2个对象如下:

[
{
"episodes": [
{
"art": {
"season.banner": "image://.jpg/",
"season.poster": "image://.jpg/",
"season.thumb": "image:.tbn/",
"tvshow.banner": ".jpg/",
"tvshow.fanart": "image:jpg/",
"tvshow.poster": "image:jpg/"
},
"episode": 1,
"episodeid": 272,
"file": "test.avi",
"label": "test1",
"originaltitle": "",
"playcount": 0,
"plot": Hello World",
"rating": 8,
"season": 2,
"thumbnail": "image.tbn/",
"title": "test1",
"tvshowid": 7
},
{
"art": {
"season.banner": "image://.jpg/",
"season.poster": "image://.jpg/",
"season.thumb": "image:.tbn/",
"tvshow.banner": ".jpg/",
"tvshow.fanart": "image:jpg/",
"tvshow.poster": "image:jpg/"
},
"episode": 2,
"episodeid": 273,
"file": "test1.avi",
"label": "test1",
"originaltitle": "",
"playcount": 0,
"plot": Hello World",
"rating": 8,
"season": 2,
"thumbnail": "image1.tbn/",
"title": "test2",
"tvshowid": 7
},
]

我试过用push进行排序,但它对我的需求来说太基本了。有人能帮忙吗?

您可以简单地对每个节目map,然后对每个集map,然后使用模板字符串创建每个对象的密钥:

shows = [{
"episodes": [
{"episode": 1, "episodeid": 272, "season": 2, "tvshowid": 7 },
{"episode": 2, "episodeid": 273, "season": 2, "tvshowid": 7 }
]
}]
const mapped = shows.map(show => show.episodes.map(o => ({
[`${o.tvshowid}.${o.season}.${o.episode}`]: o.episodeid
})))
console.log(mapped)

您可以使用reducer来获取关系数组:

const collection =
{
"episodes": [
{
"art": {
"season.banner": "image://.jpg/",
"season.poster": "image://.jpg/",
"season.thumb": "image:.tbn/",
"tvshow.banner": ".jpg/",
"tvshow.fanart": "image:jpg/",
"tvshow.poster": "image:jpg/"
},
"episode": 1,
"episodeid": 272,
"file": "test.avi",
"label": "test1",
"originaltitle": "",
"playcount": 0,
"plot": "Hello World",
"rating": 8,
"season": 2,
"thumbnail": "image.tbn/",
"title": "test1",
"tvshowid": 7
},
{
"art": {
"season.banner": "image://.jpg/",
"season.poster": "image://.jpg/",
"season.thumb": "image:.tbn/",
"tvshow.banner": ".jpg/",
"tvshow.fanart": "image:jpg/",
"tvshow.poster": "image:jpg/"
},
"episode": 2,
"episodeid": 273,
"file": "test1.avi",
"label": "test1",
"originaltitle": "",
"playcount": 0,
"plot": "Hello World",
"rating": 8,
"season": 2,
"thumbnail": "image1.tbn/",
"title": "test2",
"tvshowid": 7
},
]
}
relations = collection.episodes.reduce((acc, curr) => {
	const relation = {[curr.tvshowid + '.' + curr.season + '.' + curr.episode]: curr.episodeid}
	acc = [...acc,relation];
	return acc;
},[])
console.log(relations)

您可以使用map创建一个新数组。

var newarray = oShows.episodes.map( function(o){
return {[o.tvshowid + "." + o.season + "." + o.episode] : o.episodeid};
});
console.log(newarray);  //[{7.2.1: 272}, {7.2.2: 273}]

我试图把showid、季节和剧集作为一个组合整数。。。

这是不可能的,因为例如"7.2.1"不是整数。您的密钥将是一个字符串。

最新更新