我有以下对象数组
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)"]
};
答案 0 :(得分:1)
您可以使用.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);
答案 1 :(得分:0)
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)