简体   繁体   中英

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

I am having an object where most of the keys starting with a number and few doesnt. I am looking to remove those keys which are not starting with a number like scroll and z-index and also make a nested object with keys as numbers matching with the intial key number. This actually messed with my head. Could anyone suggest me how to acheive this? Thank you in advance.

You can iteratee through your Object.entries and look at each key with a regex to see if it starts with a number. If so, add it to the appropriate subobject:

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM