Is it possible to convert a string using object-to-object syntax?

After running a particular function, I received the following results:

[
    "users[0].name is invalid",
    "date is invalid",
    "address.ZIP is invalid"
]

I am looking for a way to convert this output from object syntax into something like this:

{
     users: [{name: 'is invalid'}],
     date: 'is invalid',
     address: {
        ZIP: 'is invalid'
    }
}

Answer №1

To properly organize the string contents, consider splitting it into separate parts representing addresses and values. By doing so, you can easily structure the data and assign appropriate values accordingly.

const
    setValue = (object, address, value) => {
        const
            hasBrackets = s => /^\[.+\]$/.test(s),
            path = address.split(/\.|(?=\[)/),
            types = path.map((_, i, a) => hasBrackets(a[i + 1]) ? [] : {}),
            keys = path.map(s => hasBrackets(s) ? s.slice(1, -1) : s),
            last = keys.pop();

        keys.reduce((r, k, i) => r[k] ??= types[i], object)[last] = value;
    },
    data = ["users[0].name is invalid", "date is invalid", "address.ZIP is invalid"],
    result = data.reduce((r, s) => {
        const [k, v] = s.match(/[^\s]+|.+$/g);
        setValue(r, k, v.slice(1));
        return r;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To simplify the keys recursively, begin by identifying the keys and then proceed to loop through the key/value pairs, reducing them into a result object.

const main = () => {
  const data = [
    "users[0].name is invalid",
    "users[0].address is invalid",
    "users[1].title is invalid",
    "date is invalid",
    "address.ZIP is invalid"
  ];

  console.log(apply(data));
};

const apply = (data) =>
  data.reduce((result, val, index) => {
    const
      pos = val.indexOf(' '),
      key = val.substring(0, pos),
      value = val.substring(pos + 1);
    applyPair(result, key, value);
    return result;
  }, {});

const applyPair = (ref, key, value) => {
  const [headKey, ...tailKeys] = key.split(/\./);
  if (headKey.endsWith(']')) {
    const [ arrKey, arrIndex ] = parseArrayKey(headKey);
    ref[arrKey] = ref[arrKey] || [];
    const obj = ref[arrKey][arrIndex] || {};
    applyPair(obj, tailKeys.join('.'), value);
    ref[arrKey][arrIndex] = obj;
  } else {
    if (tailKeys.length > 0) {
      const objKey = headKey;
      ref[objKey] = {};
      applyPair(ref[objKey], tailKeys.join('.'), value);
    } else {
      ref[key] = value;
    }
  }
};

const parseArrayKey = (key) =>
  (([m, k, i]) => [k, parseInt(i, 10)])(key.match(/^(\w+)\[(\d+)\]$/));

main();
.as-console-wrapper { top: 0; max-height: 100% !important; }

Outcome

{
  "users": [
    {
      "name": "is invalid",
      "address": "is invalid"
    },
    {
      "title": "is invalid"
    }
  ],
  "date": "is invalid",
  "address": {
    "ZIP": "is invalid"
  }
}

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

Drag and drop functionality in Angular 2 using TypeScript

Has anyone experimented with the drag and drop functionality using Angular2 RC with TypeScript? Thanks, Sanket ...

authorization for certain express routes using passport.js

Securing certain express routes with Passport.js authentication Steps for authenticating specific routes in Passport.js Looking for a method to authenticate particular routes using Passport.js Your assistance is greatly appreciated... ...

Mapped types: Specify mandatory properties depending on whether an array of identical objects includes a specific string value

Can an object property be set to required or optional based on the presence of a specific string in an array within the same object? type Operator = "A" | "B" type SomeStruct = { operators: Operator[]; someProp: string; // this should be ...

Deselect the DOM element

Here is a jQuery code snippet: $(document).ready(function () { $(".story-area > h1, .story-area > p, .story-area > div > p").text(function () { return convertString($(this).text()); }); }); Additionally, there is a function de ...

Using JavaScript to Transmit URL

Imagine I have a URL similar to this: http://localhost:8000/intranet/users/view?user_id=8823 All I aim to achieve is to extract the value from the URL using JavaScript, specifically the user_id (which is 8823 in this instance), and transmit it through an ...

Troubleshooting MongoDB query criteria in Meteor and JavaScript doesn't yield the expected results

I am encountering an issue with a Products collection that has an attribute called "productCode". My goal is to create a server-side query to fetch a product based on the productCode attribute. Unfortunately, I keep running into a "cannot read property &ap ...

json request not functioning properly in Internet Explorer and experiencing difficulties with caching

Unfortunately, the code snippet provided below is compatible only with Firefox and not Internet Explorer. The JSON file breaks when it encounters the text "Meanscoil na mBraithre Criostaí": "2028425":[19, "Awaiting Correction", "", "Meanscoil na mBra ...

How to efficiently highlight a row in a table when hovering over one of its cells, utilizing the React hook useState

I have a table displaying a list with three columns: item, delete-button-1, delete-button-2. When hovering over a delete button, the corresponding item is highlighted in red. Utilizing React Hook useState to store the index of the row where the delete bu ...

Troubleshooting JSON Parsing Issue in Android Using Volley Library

Struggling to retrieve JSON response from the server and displaying it on my Android device due to parsing errors. The server response in JSON format is as follows: { "Result": "Login Success", "User_Name:": "Ayan" } However, in Android, I am ha ...

The second occurrence of a jQuery event

When a user left-clicks on the menu, it should load a view in a draggable box. However, the functionality is not working as expected. Sometimes you need to click twice - the first time the box appears but is not draggable, and the second time a new box app ...

How can a method be called from a sibling component in Angular when it is bound through the <router-outlet>?

In my current project, I have implemented an application that utilizes HTTP calls to retrieve data from an API endpoint and then displays it on the screen. This app serves as a basic ToDo list where users can add items, view all items, delete items, and pe ...

Property 'map' is not recognized on type 'Object' and needs to be addressed

I am currently using Angular CLI: 6.0.8 and have implemented the service shown below. However, my code editor's linter keeps showing an error message that reads: [ts] Property 'map' does not exist on type 'Object'. any The error ...

Retrieving InnerHTML of a Rendered DOM Element in AngularJS

Can I retrieve the innerHTML code of a rendered element that contains an ng-repeat loop? Here is an example: <div id="container"> <div ng-repeat="e in ctrl.elements>{{e.name}}</div> </div> ...

The equation:() is malfunctioning

Here is a code snippet I'm working with: $("#button").click(function () { for (var i = 0; i < 4; i++) { setTimeout(function () { $(".rows:eq("+i+")").css("background-color", "blue"); ...

Implementing event listeners with AngularJS after making a POST request

As I delve into the world of development, please forgive my lack of knowledge. My search for solutions brought me here. I am currently working on a comment and reply app. In order to add comments to my view, I am utilizing this specific function. $scope.i ...

Using PHP, we can easily create an array and store values that are stored in variables

Hey, I currently have 2 variables set up. $firstVariable = "123"; $secondVariable = "321"; Both of these variables are dynamically calculated and subject to change based on varying circumstances. Now, I am looking to combine these values into a single ar ...

The 'string' type in React Child does not have a '.__docgenInfo' property available

When passing children to a React component and trying to determine if a 'Button' type component is among them, I used the following code snippet. export type ExampleComponentProps = { children: React.ReactNode; } export const ExampleComponent: ...

React is still unable to display images when looping, despite the use of the "require"

I am facing an issue with extracting image paths from an array using the map function. The problem is that the image path is being printed as a string instead of rendering as an image. I tried using the require keyword, but I encountered an error stating " ...

Disable the div by graying it out when the button is clicked

In my jsni form, I have implemented a click handler on the save button. When the save button is clicked, I would like the specific div to be greyed out to indicate that data is being saved. var x=$doc.createElement("div"); x.id="nn"; var lbl=$doc.createEl ...

Using a jQuery script, you can enable a back button functionality that allows users

I created a survey to assist individuals in determining where to go based on the type of ticket they have. However, I am currently facing difficulties with implementing a "Back" button that will display the previous screen or "ul" that the user saw. Initia ...