Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird data lose in javascript while converting Array into Object

I was just working with JavaScript objects and found this which i cant figure out . I created an array with few values and trying to convert that array into object using spread and new in JavaScript but for my surprise only the first value in the array is been put into the object with its type .

I have no need what exactly is happening in background

let array = [1970,1,1]
let object = new Object(array)

console.log(object)

Output :

Number {1970}

I was expecting {1970 , 1 , 1} object but actual output is Number {1970}

like image 449
Jakka rohith Avatar asked Sep 18 '26 00:09

Jakka rohith


1 Answers

to convert array to object use Object.assign

Object.assign({},[1970,1,1])

or you can populate the object with the array elements

let array = [1970,1,1];
var obj = new Object();
Array.prototype.push.apply(obj, array);
console.log(obj); 
like image 200
Ghoul Ahmed Avatar answered Sep 20 '26 12:09

Ghoul Ahmed