[英]Add the missing Object's by comparing Two array of object
我正在尝试 plot 一张图表来显示品牌的年度销售额比较,下面是两个 arrays 的年度销售额。
var current_year = [
{
total: 12941.17,
comapanyName: "Samsung",
year: "2021"
},
{
total: 17946.87,
comapanyName: "Haier",
year: "2021"
},
{
total: 3832.36,
comapanyName: "Beetel",
year: "2021"
},
{
total: 12528,
comapanyName: "Celkon",
year: "2021"
}
];
var last_year = [
{
total: 427805.51,
comapanyName: "Samsung",
year: "2020"
},
{
total: 77576.33,
comapanyName: "Godrej",
year: "2020"
},
{
total: 53389.02,
comapanyName: "Beetel",
year: "2020"
},
{
total: 100748.49,
comapanyName: "Celkon",
year: "2020"
},
{
total: 4534.19,
comapanyName: "FORD",
year: "2020"
},
{
total: 5.05,
comapanyName: "Voltas",
year: "2020"
}
];
由于 arrays 中缺少一些公司名称,因此我无法按预期对图表进行 plot。 我需要帮助将缺少的公司名称添加到相应的数组中,包括年份、名称和总数。 类似于这张图表https://apexcharts.com/react-chart-demos/line-charts/data-labels/
期待 -
这是一个可以帮助你的例子
var current_year = [
{
total: 12941.17,
comapanyName: "Samsung",
year: "2021"
},
{
total: 17946.87,
comapanyName: "Haier",
year: "2021"
},
{
total: 3832.36,
comapanyName: "Beetel",
year: "2021"
},
{
total: 12528,
comapanyName: "Celkon",
year: "2021"
}
];
var last_year = [
{
total: 427805.51,
comapanyName: "Samsung",
year: "2020"
},
{
total: 77576.33,
comapanyName: "Godrej",
year: "2020"
},
{
total: 53389.02,
comapanyName: "Beetel",
year: "2020"
},
{
total: 100748.49,
comapanyName: "Celkon",
year: "2020"
},
{
total: 4534.19,
comapanyName: "FORD",
year: "2020"
},
{
total: 5.05,
comapanyName: "Voltas",
year: "2020"
}
];
const currentYearData = {};
for (const item of current_year) {
currentYearData[item.comapanyName] = true;
}
for (const item of last_year) {
if (!currentYearData.hasOwnProperty(item.comapanyName) && item.comapanyName) {
// Company exists in last_year but not in current_year
current_year.push({ total: 0, companyName: item.comapanyName, year: "2021" });
}
}
for (const item of current_year) {
if (!last_year.find(c => c.comapanyName === item.comapanyName) && item.comapanyName) {
// Company exists in current_year but not in last_year
last_year.push({ total: 0, companyName: item.comapanyName, year: "2020" });
}
}
console.log(current_year);
console.log(last_year);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.