我需要有一个地图,其中包含键和相应的值作为数组,我该怎么做?
[
{
"language": "english",
"movie_name": "die-hard",
"movie_size": 89
},{
"language": "english",
"movie_name": "inception",
"movie_size": 40
},{
"language": "english",
"movie_name": "Lionking",
"movie_size": 50
},{
"language": "spanish",
"movie_name": "L'amour",
"movie_size": 10
},
{
"language": "spanish",
"movie_name": "L'amour",
"movie_size": 65
},{
"language": "english",
"movie_name": "inception",
"movie_size": 70
},{
"language": "english",
"movie_name": "die-hard",
"movie_size": 62
}
]
以上是我的数据结构,下面我的代码我可以形成一张地图,用于打印每种语言的电影数量。
我有一个代码fiddle,目前将以下内容打印到控制台
Map{
'english' => Map {'die-hard' => 2, 'inception' => 2, 'Lionking' => 1},
'spanish' => Map {'L'amour' => 2} }
但是我想根据电影大小计算百分位数,为此我需要基于语言的特定movie_name的所有movie_size。我不确定如何实现这一目标。
答案 0 :(得分:0)
将值设置为数组[]
和.push
以向其添加项目:
array = [ { "language": "english", "movie_name": "die-hard-4k" , "movie_size": 89 },
{ "language": "english", "movie_name": "inception-1080", "movie_size": 40 },
{ "language": "english", "movie_name": "Lionking-4k" , "movie_size": 50 },
{ "language": "spanish", "movie_name": "L'amour-1080" , "movie_size": 10 },
{ "language": "spanish", "movie_name": "L'amour-4k" , "movie_size": 65 },
{ "language": "english", "movie_name": "inception-4k" , "movie_size": 70 },
{ "language": "english", "movie_name": "die-hard-1080" , "movie_size": 62 } ]
result = {}
for (item of array) {
language = result[item.language] || (result[item.language] = {})
movie_name = item.movie_name.replace(/-[^-]*$/, '')
movie_size = language[movie_name] || (language[movie_name] = [])
movie_size.push(item.movie_size)
}
console.log(result)