sonu kumar
sonu kumar

Reputation: 143

JS- How to convert an array with key and value pairs to an object?

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.

Upvotes: 0

Views: 52

Answers (2)

Fus_ion
Fus_ion

Reputation: 41

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

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370689

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)

Upvotes: 1

Related Questions