簡體   English   中英

根據屬性將一個對象拆分為多個對象

[英]split one object into multiple objects based on the property

myObj = {1-inputWidth : '30px' , 1-inputHeight: '30px', 1-color : 'red',
        2-inputWidth : '20px' , 2-inputHeight: '10px', 2-color : 'blue',
        3-inputWidth : '60px' , 3-inputHeight: '70px', 3-color : 'white',  
        4-inputWidth : '90px' , 4-inputHeight: '10px', 4-color :'yellow', 
        scroll : 'auto', z-index : 1}
resultObj = {1: {1-inputWidth : '30px' , 1-inputHeight: '30px', 1-color : 'red'},
             2: { 2-inputWidth : '20px' , 2-inputHeight: '10px', 2-color : 'blue'}, 
             3: {3-inputWidth : '60px' , 3-inputHeight: '70px', 3-color : 'white'},  
             4: {4-inputWidth : '90px' , 4-inputHeight: '10px', 4-color :'yellow'}}

我有一個對象,其中大多數鍵以數字開頭,少數鍵不以數字開頭。 我希望刪除那些不是以滾動和 z-index 等數字開頭的鍵,並且還使用鍵作為與初始鍵號匹配的數字的嵌套對象。 這實際上搞砸了我的頭。 誰能建議我如何實現這一目標? 先感謝您。

您可以遍歷Object.entries並使用正則表達式查看每個鍵以查看它是否以數字開頭。 如果是這樣,請將其添加到適當的子對象中:

 let myObj = {'1-inputWidth' : '30px' , '1-inputHeight': '30px', '1-color' : 'red','2-inputWidth' : '20px' , '2-inputHeight': '10px', '2-color' : 'blue','3-inputWidth' : '60px' , '3-inputHeight': '70px', '3-color' : 'white', '4-inputWidth' : '90px' , '4-inputHeight': '10px', '4-color' :'yellow', scroll : 'auto', 'z-index' : 1} let o = Object.entries(myObj) .reduce((obj, [k, v]) => { let num = k.match(/^\\d+/) // get number in key? if (num) { // was there a match? if (obj[num]) obj[num][k] = v // add new entry else obj[num] = {[k]: v} } return obj }, {}) console.log(o)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM