1
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.

2
  • 2
    Is there any rationale behind objects with numeric indices? You might be interested in an array for this task. Commented Jan 18, 2019 at 3:04
  • 1
    you can use reduce function to do this. Commented Jan 18, 2019 at 3:05

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Got the result as i am expecting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.