divide a single item into several items depending on its attribute

data = {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}
newData = {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'}}

This object has keys starting with numbers and some that don't. I want to remove the non-numeric keys like scroll and z-index, and create a nested object using only the numeric keys from the original data. Can anyone help me figure this out? Thank you!

Answer №1

To identify keys that start with a number in your object, you can utilize Object.entries to iterate through each key and apply a regex check. If a key starts with a number, you can add it to the corresponding 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+/)              // extract number from key
          if (num) {                             // check for match
              if (obj[num]) obj[num][k] = v      // add new entry
              else obj[num] = {[k]: v}
          }
          return obj

       }, {})

console.log(o)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instructions on dynamically positioning a collection of div elements at the center of a webpage container

I am looking to create a set of divs that are centered on the page and adjust in size according to the length of the username. .Container1 { display: table; width: 100%; padding:0; margin:0; -webkit-box-sizing: border-box; -moz-box-sizing: bor ...

Achieve a fading effect on an element as you scroll down the page

I successfully implemented a toggle audio button on my website, but now I would like it to fade in along with the scroll-to-top button that I also have (which operates similarly to the buttons on scrolltotop.com). Is there a simple way to achieve this? He ...

endless cycle of scrolling for div tags

My goal is to incorporate a tweet scroller on I believe it uses the tweet-scroller from Unfortunately, this link seems broken as the demo is not functioning. I searched for an alternative solution and came across http://jsfiddle.net/doktormolle/4c5tt/ ...

The template failed to load on AngularJS post-compilation

Following the build of my Angular app, I encountered this error message: [$compile:tpload] Failed to load template: app/app.html (HTTP status: 404 Not Found). Seeking assistance from you all!!!!! app.html <div class="root"> <div ui-view> ...

The OpenWeatherMap API is displaying 'undefined' as a response

I've been encountering some issues with my weather app project due to lack of clarity in my previous questions. To be more specific, every time I attempt to retrieve weather information in JSON format using the fetch method, it keeps returning undefin ...

Can the color of an ion-radio be adjusted when it is not selected?

I am experiencing an issue where I need to change the default color (grey) to a specific color of my choice, such as the primary color. I have attempted the following methods: <ion-col sizeXs="12" sizeMd="6" class="radio-box"> <ion-item line ...

It appears that Apexcharts is not compatible with React/Next.js

Issue Encountering a crash in my Next.js/React/Node application whenever I utilize import Chart from "react-apexcharts" in any file. Upon attempting to access the app, an error message is displayed: Server Error ReferenceError: window is not ...

Sharing AngularJs controllers between different modules can help streamline your

I'm facing an issue with trying to access an array from one controller in another controller. Despite simplifying the code for clarity, I still can't seem to make it work. Here is my first controller: app.controller('mycont1', [' ...

Showing headings in the table vertically

I have a header1 and header2 with corresponding data1 and data2 that I want to display differently. h h e e a a d d e e r r 1 2 data1 data2 To enhance the presentation, I wish to add borders around the head ...

When using child_process to run a Python script in Node.js, a promise may not resolve properly if the process exits before all

Currently, I am facing an issue while trying to execute sublist3r within a node app. The script runs successfully but only displays the banner before abruptly exiting after about 5 seconds. Typically, the script should interact with the web and take approx ...

Why won't my setTimeout function work?

I'm having trouble working with the setTimeout function, as it doesn't seem to be functioning properly. First and foremost, Player.prototype.playByUrl = function (url) { this.object.data = url; return this.play(); } The co ...

Unable to initiate the server in a new window due to the absence of a specified terminal application

When incorporating an external library into my React Native project, the installation process is usually smooth. However, when I try to integrate the library into my entire project and run 'react-native run-android' command, it shows an error. I ...

The issue of actions failing to flow from sagas to reducers in React.js

Upon user login, the success response is received but the action is not passed to the reducer. Strangely, during user registration, everything works smoothly. //saga.js import { put, takeEvery, all, call } from 'redux-saga/effects'; import {getRe ...

There seems to be an issue with posting JSON data correctly

Currently, I am attempting to include an object with numerous attributes within it. This is the object I am trying to use with $.post: ({"fname" : fname, "lname" : lname, "gender" : gender, "traits" : { "iq" : inte ...

Please refrain from submitting the form until the slow AJAX jQuery process has finished

My form is experiencing a delay of almost 4 seconds due to the Ajax jQuery I am using, which creates fields within the form. This delay causes some users to submit the form before the necessary fields are created. I need a way to prevent the form from bein ...

Tips for patiently waiting for a series of asynchronous calls to successfully complete

I have a scenario where I am dealing with multiple asynchronous calls that are dependent on each other's success. For example: function1 = () => { /*Some required Logic*/ return fetch("myurl") .then((json) => { functi ...

Is there a way to maintain the original indexing of a list after users have selected a filtered item in React using Webpack?

After implementing a filter (filteredCat) for my catalogue, the visual display works as expected. One issue I am facing is that even though the items are filtered, the logged index does not correspond to the new filtered list but instead reflects the inde ...

Transforming images with Imagick

I've been trying to generate thumbnails from PDF uploads using Imagick. I have a script that is supposed to handle this task, but unfortunately, it only uploads the file without creating a thumbnail. I know some of you may find this basic, but PHP is ...

Angular's Conditional ng-if Error

Encountering an error link from Angular Js [1]http://errors.angularjs.org/1.2.10/$parse/lexerr?p0=Unterminated%20quote&p1=s%2013-14%20%5B'%5D&p2=recipe.ID%20!%3D%3D' I am struggling to implement the solution for this error. Any help wou ...

Choose the tab labeled "2" within a segment of the webpage

index.html#section takes you to a specific section of a webpage. However, I am interested in picking the second tab within a section of the page. I'm uncertain if this can be achieved without relying on JavaScript, but employing the Tab Content Script ...