Asking
Asking

Reputation: 4192

Crate an object with unique key in Javascript

I want to create an object with unique key like:

let id = Symbol("id");
let id2 = Symbol("id");

const obj = {
      [id]: ()=>  'test'
}


console.log(obj[id]())

In the case above, i can access the return value only if i have the Symbol. And this works.
Question: How to create a condition to avoid the error id is not defined if i do this:

//let id = Symbol("id");
//let id2 = Symbol("id");

const obj = {
      [id]: ()=>  'test'
}


console.log(obj[id]())

So in this case i don't want to get an error but just to get the empty object or something like this. How to handle this?

Upvotes: 0

Views: 65

Answers (3)

Sunil Kumar
Sunil Kumar

Reputation: 420

you can check the property existence in that object before calling it, refer hasOwnProperty

    let id = Symbol("id");
    let id2 = Symbol("id");

    const obj = {
          [id]: ()=>  'test'
    }

    if (obj.hasOwnProperty(id2)) { // false 
      console.log(obj[id2]());
    }
    
    if (obj.hasOwnProperty(id)) { // true
      console.log(obj[id]()); 
    }

id2 won't be printed because that property not exist in the object but id does

Upvotes: 1

farvilain
farvilain

Reputation: 2562

There is no point to check for undeclared variable errors or so, this is just crapy.

If your goal is just to build an object with some method, built it just simply as:

const test = () => 'test';

const obj1 = { somethingYouWant: test };
const obj2 = { id: test };
const obj3 = { otherThing: test };

Upvotes: 0

Md Sabbir Alam
Md Sabbir Alam

Reputation: 5054

You can use try-catch block.

try {
    const obj = {
      [id]: ()=>  'test'
    }
} catch(err) { console.log('test error catched. Do what you want to do here.'); }

Upvotes: 0

Related Questions