2 回答

TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以映射所需的鍵,以便為每個(gè)屬性構(gòu)建一個(gè)數(shù)組。
const
KEYS = ['b', 'a', 'c'],
object = { 2018: { a: 1, b: 2, c: 3 }, 2019: { a: 4, b: 5, c: 6 }, 2020: { a: 7, b: 8, c: 9 } },
result = Object.fromEntries(Object.entries(object).map(([k, o]) => [
k,
Object.fromEntries(Object.entries(o).map(([l, v]) => [
l,
KEYS.map(m => l === m ? v : 0)
]))
]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
Object.entries您可以使用和的組合Object.fromEntries來(lái)映射對(duì)象,然后只需創(chuàng)建一個(gè)長(zhǎng)度為 KEYS arr 的新數(shù)組。
const KEYS = ['b', 'a', 'c']
const obj = {
2018: {a: 1, b: 2, c: 3},
2019: {a: 4, b: 5, c: 6},
2020: {a: 7, b: 8, c: 9},
}
const result = Object.fromEntries( // Create obj from array of entries
Object.entries(obj).map(([key, value]) => [ // create array of entries from obj and map it
key,
Object.fromEntries( // do the same obj/arr transformation on the value
Object.entries(value).map(([subKey, subValue]) => {
const arr = new Array(KEYS.length).fill(0); // create new array of keys length and fill all zeroes
arr[KEYS.indexOf(subKey)] = subValue; // on the index of the key in the KEYS arr, set the value of the key
return [subKey, arr]; // return subValue
})
)
])
);
console.log(result);
添加回答
舉報(bào)