第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

根據(jù)鍵數(shù)組更改數(shù)據(jù)集對(duì)象的形狀

根據(jù)鍵數(shù)組更改數(shù)據(jù)集對(duì)象的形狀

猛跑小豬 2023-05-19 19:57:01
假設(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 = { 2018: {     a: [0, 1, 0],     b: [2, 0, 0],     c: [0, 0, 3]   }, 2019: {     a: [0, 4, 0],     b: [5, 0, 0],     c: [0, 0, 6]   },, 2020: {     a: [0, 7, 0],     b: [8, 0, 0],     c: [0, 0, 9]   },}result['2018'] 對(duì)象具有三個(gè)鍵。每個(gè)鍵值都是一個(gè)數(shù)組,其中包含按 KEYS 使用 0 作為填充值設(shè)置的順序排列的值。我怎么能做這樣的事情?這是我嘗試過(guò)的,但顯然比這更復(fù)雜:const reshaped = Object.entries(obj).map(([key, value]) => {  return { [key]: Object.values(value) }})// [//  { 2018: [ 1, 2, 3 ] },//  { 2019: [ 4, 5, 6 ] },//  { 2020: [ 7, 8, 9 ] }// ]
查看完整描述

2 回答

?
德瑪西亞99

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; }


查看完整回答
反對(duì) 回復(fù) 2023-05-19
?
LEATH

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);


查看完整回答
反對(duì) 回復(fù) 2023-05-19
  • 2 回答
  • 0 關(guān)注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)