bet*_*eth 5 javascript arrays object
我有以下数组:
const countries = ['Belgium', 'Uk']
const years = ['2019', '2018', '2017']
const colors = ['red', 'orange', 'green']
Run Code Online (Sandbox Code Playgroud)
我想要一个这样的数组:
const result = [
{
country: 'Belgium',
year: '2019',
red: random(min, max),
orange: random(min, max),
green: random(min, max),
},
{
country: 'Belgium',
year: '2018',
red: random(min, max),
orange: random(min, max),
green: random(min, max),
},
{
country: 'Belgium',
year: '2017',
red: random(min, max),
orange: random(min, max),
green: random(min, max),
},
{
country: 'Uk',
year: '2019',
red: random(min, max),
orange: random(min, max),
green: random(min, max),
},
{
country: 'Uk',
year: '2018',
red: random(min, max),
orange: random(min, max),
green: random(min, max),
},
{
country: 'Uk',
year: '2017',
red: random(min, max),
orange: random(min, max),
green: random(min, max),
},
{
country: 'Tot',
year: '2019',
red: // sum of the values of the red key for each country in the year 2019,
orange: // sum of the values of the orange key for each country in the year 2019,
green: // sum of the values of the green key for each country in the year 2019,
},
{
country: 'Tot',
year: '2018',
red: // sum of the values of the red key for each country in the year 2018,
orange: // sum of the values of the orange key for each country in the year 2018,
green: // sum of the values of the green key for each country in the year 2018,
},
{
country: 'Tot',
year: '2017',
red: // sum of the values of the red key for each country in the year 2017,
orange: // sum of the values of the orange key for each country in the year 2017,
green: // sum of the values of the green key for each country in the year 2017,
},
]
Run Code Online (Sandbox Code Playgroud)
因此,对于每年和每个国家,必须有一个包含每种颜色的键的对象.该值必须是随机的.
然后,应该是具有country = Total和使用颜色值的其他对象键入其他对象的值的总和.
这就是我想要做的:
function createValues() {
const min = 0
const max = 300
const dataset: any = []
countries.forEach(country => {years.forEach(year => {colors.forEach(color => {dataset.push({country: country, year: year, [color]: random(min, max),})})})})}
Run Code Online (Sandbox Code Playgroud)
但它不起作用,我不知道如何计算总和值.