繁体   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