gpt4 book ai didi

javascript - JS 将值推送到对象数组

转载 作者:行者123 更新时间:2023-12-03 00:02:56 25 4
gpt4 key购买 nike

我有以下对象数组

 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”推送到“data”键,将所有值从“国家/地区名称”推送到“labels”键。

我尝试过 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);

关于javascript - JS 将值推送到对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55094842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com