user2649476
user2649476

Reputation: 53

Convert text to object

I have a string, something like this below

const UID = "befjbljfbelgvfghvgjhsv";
console.log(typeof(UID), UID);
string befjbljfbelgvfghvgjhsv

I have a utility which takes the above string format (a unique ID) but in type object format. It needs to be in object type and but string looking. So I want to convert the above string to object type.

so basically I want some thing like:

convertedUID = ???
console.log(typeof(convertedUID), convertedUID);
object befjbljfbelgvfghvgjhsv

Any quick hacks?

Upvotes: 2

Views: 312

Answers (2)

kanine
kanine

Reputation: 1108

You can think of a wrapper method, let's call it objectify

function objectify(val){
    var obj = {
        toString: function(){
            return val
        },
        valueOf: function(){return val}
    }
    return obj
}
var x= objectify('this_is_a_string');
console.log(typeof(x) + ' ' + x);

// can be used as a key as well
// mostly all operations what work on a string.
var y={};
y[x] = 456;
console.log(y['this_is_a_string']);

Don't expect console.log(typeof(x), x); to work like you asked for.
console.log(typeof(x) + ' ' + x); would work as string concatenation would force a coercion.

Upvotes: 1

Mechanic
Mechanic

Reputation: 5380

There is no object like object befjbljfbelgvfghvgjhsv in javascript;

object must have a key, value pair (e.g. { text: "befjbljfbelgvfghvgjhsv" }) and you can convert your string to object by creating a new object, and assigning your string to a key in it; but the key name matters, the function you are going to pass that object probably expect a specific key name. check the snippet below:

const UID = "befjbljfbelgvfghvgjhsv";
const newObject = { text : "befjbljfbelgvfghvgjhsv" }
console.log(typeof(newObject), newObject.text);

Upvotes: 0

Related Questions