0
var arr = [];
arr['k1'] = 100;
console.log(arr); //o/p - [k1: 100]
arr.length;       //o/p - 0
window.copy(arr);   //copies: []

I want to convert this array-like object to a proper obj i.e,

arr = { k1: 100}

So doing window.copy(arr) should copy {k1:100}

NOTE- I need to do this as Node.js express server returns empty arrays in response for such cases.

2
  • 4
    Why not use an object to begin with? That's not what an array should be used for Commented Dec 23, 2020 at 17:20
  • 2
    arr['k1'] = 100 doesn't do what you think it does. It doesn't create an index called k1 with a value of 100. It creates an entirely new property on this instance of an Array called k1 and sets the value to 100. If you were to loop over the array indexes, you'd never see k1 show up and it is why the .length is 0. Commented Dec 23, 2020 at 17:30

2 Answers 2

1

You can use object spread syntax to copy all own enumerable properties from the original object to a new object:

const arr = [];
arr['k1'] = 100;
const obj = { ...arr };

console.log(obj);

This works even if arr is originally an array, rather than a plain object, because the k1 property exists directly on the array.

(But ideally, one should never have code that assigns to arbitrary properties of an array - better to refactor it to use an object in such a situation to begin with)

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

Comments

1

var array = []
array["k1"] = 100;
var newObject = Object.assign({},array);
console.log(newObject);

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.