TypeScript code to transform an array of strings into a custom object

I have a specific requirement that I have partially achieved using Java, but now I need to transition it to TypeScript on the client side.

Please note: The input provided below is for illustrative purposes and may vary dynamically.

Input:

var input = ["a.name", "a.type", "b.city.name" , "b.city.zip", "b.desc","c"];

We are looking to develop a utility function that takes the input above and generates output as shown below:

Output:

The output should be a string, not an object or any other data type.

"{ a { name, type }, b { city  {name, zip } , desc },  c }"

Any assistance with this would be greatly appreciated.

Answer №1

While TypeScript may not directly relate to your question, here is a solution for creating the string format you specified. I start by converting the array into an object with the specified properties, and then utilize a function to convert the object into the desired string format.

const input = ["a.name", "a.type", "b.city.name" , "b.city.zip", "b.desc","c"];

const arrayToObject = (arr) => {
  return arr.reduce((result, val) => {
    const path = val.split('.');
    let obj = result;
    path.forEach(key => {
      obj[key] = obj[key] || {};
      obj = obj[key];
    });
    return result;
  }, {});
}

const objectToString = (obj, name = '') => {
  const keys = Object.keys(obj);
  if (keys.length === 0) {
    return name;
  } 
  
  return `${name} { ${keys.map(k => objectToString(obj[k], k)).join(', ')} }`;
}

const arrayToString = arr => objectToString(arrayToObject(arr));

console.log(arrayToString(input));

Answer №2

Here's an elegant approach. The key is to recursively parse the strings and save the interim outcomes in an Object.

    function convertDotStringToObject(remainder, parent) {
      if (remainder.indexOf('.') === -1) {
      return parent[remainder] = true
      } else {
    var parts = remainder.split('.');
        convertDotStringToObject(parts.slice(1).join('.'), (parent[parts[0]] || (parent[parts[0]] = {})))
      }
    }
    
    var result = {};
    ["a.name", "a.type", "b.city.name" , "b.city.zip", "b.desc","c"].forEach(function(item) {
    convertDotStringToObject(item, result)
    });
    
    var final = JSON.stringify(result).replace(/\"/gi, ' ').replace(/\:|true/gi, '').replace(/\s,\s/gi, ', ');
    console.log(final)
    // Outputs: { a { name, type }, b { city { name, zip }, desc }, c }

Answer №3

Here is a possible solution:

var categories = ["category1.name", "category1.type", "category2.city.name", "category2.city.zip", "category2.desc", "category3"];
var result = {};
for(var index = 0; index < categories.length; index+=2){
    result[String.fromCharCode(index+97)] = {};
    result[String.fromCharCode(index+97)].name = categories[index];
    result[String.fromCharCode(index+97)].type = categories[index+1];
}
console.log(JSON.stringify(result));

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

Unable to modify translation values in an existing ngx-translate object

I am facing an issue where I am unable to change the value of an object property within a translation JSON file using ngx translate. Despite attempting to update the value dynamically when receiving data from an API, it seems to remain unchanged. I have t ...

The response from getStaticProps in Next.js is not valid

While following the Next.js documentation, I attempted to retrieve data from a local server but encountered an error message: FetchError: invalid json response body at http://localhost:3000/agency/all reason: Unexpected token < in JSON at position 0 ...

Understanding how to accurately pair specific data points with their corresponding time intervals on a chart

I'm currently working with apexcharts and facing an issue with timestamps. I have data for sender and receiver, each having their own timestamps. The x-axis of the graph is based on these timestamps, but I am struggling to map the timestamp with its r ...

Updating front end data using Node.js - A Comprehensive Guide

I am looking to create a website using node.js that can dynamically display a plot and update the data every minute without needing to refresh the entire page. As someone new to node.js, I am interested in learning how to use "get" requests to update the d ...

Delete auto-generated list using handlebars JS

I have successfully created a dynamic list using Handlebars.js and its template. However, I am now facing confusion on how to remove or delete items from the list using a function or specific code. As I am new to Handlebars, I would appreciate any help. ...

What is the method to obtain the keycode for a key combination in JavaScript?

$(document).on('keydown', function(event) { performAction(event); event.preventDefault(); }); By using the code above, I am successful in capturing the keycode for a single key press. However, when attempting to use a combin ...

Issue: anticipated ']' after statement in sanity in conjunction with nextjs

Struggling to retrieve data from Sanity in Next.js, but encountering an error that reads: "Error: expected ']' following expression." As a beginner in this, I've been trying to troubleshoot it, but I'm unsure of the root cause of the er ...

Remove an image that has been selected while uploading multiple images using AngularJS

If I want to delete a specific image from multiple uploads by clicking on the image in AngularJS, how can I achieve this? Each uploaded image has an associated textbox. When the delete icon on the image is clicked, both the image and the corresponding text ...

Insert a percentage sign into a right-aligned text box

I am trying to figure out how to permanently display a % symbol at the far right side of a textbox that shows a percentage. Can anyone help me with this? ...

Sorting of array in AngularJS ngRepeat may result in changing the length of the array

Link to JSFiddle: http://jsfiddle.net/WdVDh/101/. When updating the sorting option for an ng-repeat list, I noticed that the array length changes and in my local version, all items disappear. My code involves filtering and sorting, with the ability to fi ...

Modify the form's action attribute when submitted

I am trying to create a form with multiple buttons that will change the action and target properties when a specific button is clicked. Below is my code snippet: <div id="root"> <form :action="form.action" ref="form" :target="form.target"&g ...

Ways to establish a default option in a dropdown menu using JavaScript

I am currently attempting to link a JSON object to a dropdown in the following manner: JSON data "securityQuestions": [ "First Pet's Name", "City I was born in", "Mother's Maiden Name", "Favorite teacher's Name" ] This i ...

Tips on using Ajax to post in HTML

Here is the code I have been working on: <script type="text/javascript"> var xmlDoc; var xmlhttp; function loadRates() { xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = readRates; xmlhttp.open("GE ...

MUI Tutorial: Displaying Text with Line Breaks

Whenever I input text into the MUI Textfield, it displays without any line breaks. Is there a more effective solution available? <Stack direction="row" alignItems="start" justifyContent="start" mb={5}> <TextFie ...

Guide on detecting and capturing a change in location history event

My main goal is to capture router change events outside of the NextJS framework, not within it. The application I have developed using NextJS includes some code that operates independently of the NextJS context. This code needs to be able to detect navigat ...

Execute the function when the form is submitted and show the total of the two values

I am currently working on a straightforward custom module for Drupal 7. This module takes two numeric values and upon submission, displays the sum of these values on the same page. While I have the form set up, it is not yet complete. I am facing some dif ...

Customize time formatting in Angular to accommodate localized time formats

I am utilizing Angular's localization service version 8.3.28 to support English, Spanish (Mexico) with code es-MX, and Spanish (Spain) with code es-SP While using the date pipe: {{ foo.Date | date: 'shortDate' }} The dates are changing to ...

Issue encountered when importing async function: Invalid hook call. Hooks are designed to be called only within the body of a function component

All I desire is the ability to access logic from my geolocationApi file in my react-native components without using a hook. Instead, I prefer normal asynchronous functions. The geolocationApi file employs a custom hook for handling mobx state updates, whic ...

Troubleshoot: jQuery Datalink functionality not functioning properly with object methods

Within my JavaScript code, I have defined an object that includes various properties and an instance method that calculates a value based on two of those properties. To synchronize the object's property values with form elements in the UI, I am utili ...

Navigating through this object with PUG and Express: a step-by-step guide

I am currently working on a basic blockchain project to practice my skills with nodejs. I have created a blockchain object that consists of a block class, and now I want to loop through this object using pug. app.get('/', function(request, respon ...