skip to Main Content

I’m trying to have the key of the object not be surrounded by single quotes.

let arr= [2, 3, 4, 11];
let myObj={};
myObj[arr[2]]=true;
console.log(myObj);

The above code outputs the result { ‘4’: true }

How do I remove the single quotes around 4 and have it display as { 4: true }

2

Answers


  1. Just that chunk of code you have should be producing the result {4:true}. Either way, it would be storing the info correctly

    Login or Signup to reply.
  2. You can do it like so:

    const arr = [2, 3, 4, 11];
    const myObj = {};
    myObj[arr[2]] = true;
    const str = JSON.stringify(myObj);
    console.log(str.replace(/[",']/g, ''));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search