3

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}

2
  • 2
    I cannot reproduce this in Chrome 75.0. Commented Jul 16, 2019 at 13:46
  • 2
    "trying to convert that array into object" - what? An array object already is an object. So what do you actually want to achieve? Commented Jul 16, 2019 at 14:11

4 Answers 4

2

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); 

Sign up to request clarification or add additional context in comments.

2 Comments

Can you tell me whats up with my approach why all other values expect the first is discarded
you cannot use array as constructor for Object , to fix your approach, you should use let obj = new Object(); Array.prototype.push.apply(obj, array);
2

The closest thing you could do is:

const object = {...array}

Which will give you the output:

{0: 1970, 1:1, 2:1}

3 Comments

Yes. Can you tell me what is wrong with my approach
In general you should avoid using the literal constructor new Object. If you pass an array to it will just return the array back.
when using the spread operator const obj = {...array} you are telling: Hey make me an object with a property for each item of this array, and this property name will be the element's index
1

You can try with Object.assign()

let array = [1970,1,1];
let object = Object.assign({}, array);
console.log(object);

Comments

0

It works in the Chrome (Version 75).

Check the following code, if in case you are expecting the following behavior.

CODE:

let array = [1970,1,1];
let obj = {}, i = 0;
for(var element in array) obj[i++] = array[element];
console.log(obj);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.