我正在努力尋找一種優雅可靠的方式來合并 vanilla JS 或 d3.js 中的兩個陣列,其中
- 系列的“行”不一定匹配;
- 物件可能共享一些但不是全部屬性;
- “缺失”屬性填寫為空。
例如,兩個陣列的形式
A =
[
{
year : 2001,
gdp : 1.1,
population : 1100
},
{
year : 2002,
gdp : 1.2,
population : 1200
},
]
B =
[
{
year : 2000,
gdp : 1.0,
rainfall : 100
},
{
year : 2001,
gdp : 1.1,
rainfall : 110
}
]
理想情況下會結合給
C =
[
{
year : 2000,
gdp : 1.0,
population : null,
rainfall : 10
},
{
year : 2001,
gdp : 1.1,
population : 1100,
rainfall : 110
},
{
year : 2002,
gdp : 1.2,
population : 1200,
rainfall : null
},
]
我通常可以弄清楚這種事情,但這個讓我真的卡住了!
uj5u.com熱心網友回復:
您可以構建所有專案的陣列,獲取鍵并構建一個空物件作為空物件的模式。然后分組year并獲取值。必要時應用排序。
const
a = [{ year: 2001, gdp: 1.1, population: 1100 }, { year: 2002, gdp: 1.2, population: 1200 }],
b = [{ year: 2000, gdp: 1.0, rainfall: 100 }, { year: 2001, gdp: 1.1, rainfall: 110 }],
items = [...a, ...b],
empty = Object.fromEntries(Object.keys(Object.assign({}, ...items)).map(k => [k, null])),
result = Object
.values(items.reduce((r, o) => {
r[o.year] ??= { ...empty };
Object.assign(r[o.year], o);
return r;
}, {}))
.sort((a, b) => a.year - b.year);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/504319.html
標籤:javascript d3.js 数据操作
