Home > Enterprise >  How check difference between string and object string in Javascript?
How check difference between string and object string in Javascript?

Time:09-04

I have 2 strings like this:

var a = 'Mario'; 
var b = '{title: 'Luigi', age: 38}';

and I want the new variable:

 c = 'Mario'; 
 d = {title: 'Luigi', age: 38}; 

How can I check the difference between a and b in the if condition?

I tryed with JSON.parse(); but it doens't work with the variable a. The code I write is:

if( typeof(JSON.parse(x)) != 'object'){
  //then I want simply x that is a string
}else{
 //then I want JSON.parse(x) that is an object
}

Let's say that I have a database where there are saved all strings like 'a'. Now I want also save strings like 'b' at the same voice of database. In other words, in the database there are all strings, but some of them are strings like 'b' and I need to write something like b.title

I hope is much clear

Thanks!

CodePudding user response:

The question was not clear to me but what I got is you want to differentiate between a string and string-object.
If so, use JSON.parse with try - catch block.

const a = 'Mario'; 
const b = "{'title': 'Luigi', 'age': '38'}";
const [c,d] = [a, b].map((e) => {
    try {
        return (JSON.parse(e))
    } catch (error) {
        return e
    }
})

Hope this helps you!

  • Related