[英]Js push value to object array
i have the following object array 我有以下对象数组
datasets: [{
data: [],
backgroundColor: [
"#FF6384",
"#4BC0C0",
"#FFCE56",
"#E7E9ED",
"#36A2EB"
],
label: 'My dataset' // for legend
}],
labels: []
};
and i have another object array like bellow 我还有另一个像波纹管这样的对象数组
[
{
"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"
}
what i want to is to push all the value from 'nocontainers' to 'data' key and value from 'Country Name' to 'labels' key in first array. 我想要的是在第一个数组中将所有值从“ nocontainers”推入“数据”键,并将值从“国家名称”推入“标签”键。
i have tried array.push but didn't work, my final array should look like bellow 我已经尝试了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)"]
};
You can create your object using .map
with destructuring assignment to pull out the required properties from your countries
object. 您可以使用具有.map
分配的 .map
创建对象,以从countries
对象中拉出所需的属性。
See working example below: 请参见下面的工作示例:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.