[英]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.我希望删除那些不是以滚动和 z-index 等数字开头的键,并且还使用键作为与初始键号匹配的数字的嵌套对象。 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.您可以遍历Object.entries
并使用正则表达式查看每个键以查看它是否以数字开头。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.