我有以下对象数组
datasets: [{
data: [],
backgroundColor: [
"#FF6384",
"#4BC0C0",
"#FFCE56",
"#E7E9ED",
"#36A2EB"
],
label: 'My dataset' // for legend
}],
labels: []
};
我有另一个对象数组如波纹管
[
{
"PORT": "MY",
"Country Name": "AUSTRALIA",
"nocontainers": "1017"
},
{
"PORT": "MY"
"Country Name": "CAMBODIA",
"nocontainers": "1"
},
{
"PORT": "DE"
"Country Name": "CHINA",
"nocontainers": "13846"
},
{
"PORT": "DE"
"Country Name": "HONG KONG",
"nocontainers": "252"
},
{
"PORT": "MY"
"Country Name": "INDONESIA",
"nocontainers": "208"
}
我想要的是将“nocontainers”中的所有值从“数据”键和值从“国家名称”推送到第一个数组中的“标签”键。
我试过array.push但是没有用,我的最后一个数组应该看起来像下面
datasets: [{
data: [1017, 1, 13846, 252, 208],
backgroundColor: [
"#FF6384",
"#4BC0C0",
"#FFCE56",
"#E7E9ED",
"#36A2EB"
],
label: 'My dataset' // for legend
}],
labels: ["AUSTRALIA (MY)","CAMBODIA (MY)","CHINA (DE)","HONG KONG (DE)","INDONESIA (MY)"]
};
您可以使用带有.map
的destructuring assignment创建对象,以从countries
对象中提取所需的属性。
见下面的工作示例:
const countries = [{PORT:"MY","Country Name":"AUSTRALIA",nocontainers:"1017"},{PORT:"MY","Country Name":"CAMBODIA",nocontainers:"1"},{PORT:"DE","Country Name":"CHINA",nocontainers:"13846"},{PORT:"DE","Country Name":"HONG KONG",nocontainers:"252"},{PORT:"MY","Country Name":"INDONESIA",nocontainers:"208"}];
const obj = {
datasets: {
data: [],
backgroundColor: ["#FF6384", "#4BC0C0", "#FFCE56", "#E7E9ED", "#36A2EB"],
label: 'My dataset'
},
labels: []
};
obj.datasets.data = countries.map(({nocontainers: nc}) => +nc);
obj.labels = countries.map(({"Country Name": cn, PORT: p}) => `${cn} (${p})`);
console.log(obj);
let data = {
datasets: {
data: [],
backgroundColor: [
"#FF6384",
"#4BC0C0",
"#FFCE56",
"#E7E9ED",
"#36A2EB"
],
label: 'My dataset' // for legend
},
labels: []
}
let arr = [{
"Country Name": "AUSTRALIA",
"nocontainers": "1017"
},
{
"Country Name": "CAMBODIA",
"nocontainers": "1"
},
{
"Country Name": "CHINA",
"nocontainers": "13846"
},
{
"Country Name": "HONG KONG",
"nocontainers": "252"
},
{
"Country Name": "INDONESIA",
"nocontainers": "208"
}
]
arr.forEach(a => {
data.datasets.data.push(a['nocontainers'])
data.labels.push(a['Country Name'])
})
console.log(data)