Home > Enterprise >  Parse a string with a key and value to an object
Parse a string with a key and value to an object

Time:02-02

[Edited because my question was not clear]

I would like to parse each string from an array into an object as its key with an assigned value e.x.:

There is an array called dates.

This is dates[0]

"2022-02-01"

And I would like to parse it in an object that looks like this:

let datesObj = { "2022-02-01": {selected: true, marked: true} }

I have looked into JSON.parse() but I have not been able to apply it to my needs in this case (if that is even the solution).

I haven't been able to find a suitable solution, so a big thank you to anyone willing to help.

CodePudding user response:

wrap your string with breakets

var mystring='{"2022-02-01": {selected: true, marked: true}}'; 

and then try parsing it with

var myobj=JSON.parse(mystring);

CodePudding user response:

Like this?

function parse(date)
{
    const res = {}
    res[date] = {
        selected: true, 
        marked: true
    }
    return res;
}
  •  Tags:  
  • Related