简体   繁体   中英

How to convert a single string to object

I have multiple objects and trying to do a condition based on the object name. I am trying to check the name of the object based on the variable, which is a string. Is there any way to convert a single value string to object

 const showHtml= {
                 one: {
                      code: "<DIV>",
                       pos: "1" 
                 },
                 two: {
                      code: "<Body>",
                      pos: "2"
                  }
     } 
      const showcss= {
                 one: {
                      code: "text-align",
                       pos: "1" 
                 },
                 two: {
                      code: "float",
                      pos: "2"
                  }
     }  

I have a string variable (showHTML and showcss). I want to return the code based on the variable, so i am doing

 let uVariable = localstorage.getItem("ftype")
console.log(uVariable.one.code)

I should get

   <DIV>

but as i am passing the string, I can't get the object name, is there any way to convert the uVariable into object?

Thank you

You want JSON.parse here. Localstorage only stores strings. In your case, the code would look something like this:

let uVariable = JSON.parse(localstorage.getItem("ftype"))
console.log(uVariable.one.code)

String => object, use JSON.parse Object => string, use JSON.stringify

please read this code, might help you so initially we have variable showHtml which contains json data.

you should try this

JSON.parse(localStorage.getItem('showHtml')).one.code

and you can try jsfiddle: https://jsfiddle.net/dupinderdhiman/f5wz7Lv1/2/

for more explanation read below:

  var showHtml= {
                     one: {
                          code: "<DIV>",
                           pos: "1" 
                     },
                     two: {
                          code: "<Body>",
                          pos: "2"
                      }
         } 
          var showcss= {
                     one: {
                          code: "text-align",
                           pos: "1" 
                     },
                     two: {
                          code: "float",
                          pos: "2"
                      }
         }  



         localStorage.setItem('showcss', JSON.stringify(showcss));
localStorage.setItem('showHtml', JSON.stringify(showHtml));

alert('showHtml '+JSON.parse(localStorage.getItem('showHtml')).one.code);

alert('showCss '+JSON.parse(localStorage.getItem('showcss')).one.code)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM