2 回答
TA贡献1770条经验 获得超3个赞
您可以映射所需的键,以便为每个属性构建一个数组。
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贡献1936条经验 获得超6个赞
Object.entries您可以使用和的组合Object.fromEntries来映射对象,然后只需创建一个长度为 KEYS arr 的新数组。
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);
添加回答
举报