Converting other data types to objects Flashcards

1
Q

To convert a number to an object, use the Number() constructor:

A

let num = 42;
let obj = new Number(num);
console.log(obj); // outputs Number { [[PrimitiveValue]]: 42 }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

To convert an array to an object, use the Object.assign() method:

A

let arr = [1, 2, 3];
let obj = Object.assign({}, arr);
console.log(obj); // outputs { ‘0’: 1, ‘1’: 2, ‘2’: 3 }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

To convert a string to an object, use the JSON.parse() method:

A

let str = ‘{“name”: “John”, “age”: 30}’;
let obj = JSON.parse(str);
console.log(obj); // outputs { name: ‘John’, age: 30 }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly