Categories
JavaScript Answers

How to get the length of a JavaScript associative array?

To get the length of a JavaScript associative array, we use the Object.keys method.

For instance, we write

const quesArr = {};
quesArr["q101"] = "Your name?";
quesArr["q102"] = "Your age?";
quesArr["q103"] = "Your school?";
console.log(Object.keys(quesArr).length);

to call Object.keys to get the property keys of quesArr in an array.

Then we use the array’s length property to get the length of the associative array.

Categories
JavaScript Answers

How to add items to an object with JavaScript?

To add items to an object with JavaScript, we assign the value to a property.

For instance, we write

const sendData = { field1: value1, field2: value2 };

sendData.field3 = value3;

to define the sendData object.

And then we set the field3 property to value3.

Categories
JavaScript Answers

How to clone an object in JavaScript?

To clone an object in JavaScript, we can use JSON methods.

For instance, we write

const newObj = JSON.parse(JSON.stringify(oldObj));

to call JSON.stringify to convert oldObj into a JSON string.

And then we call JSON.parse to parse the JSON string back to an object.

Dates will be converted to strings with stringify so the parsed object will have date strings instead of date objects for dates.

Categories
JavaScript Answers

How to convert object to array using JavaScript?

To convert object to array using JavaScript, we use the Object.values method.

For instance, we write

const arr = Object.values(inputObj);

to call Object.values with inputObj to return an array of the inputObj property values in it.

Categories
JavaScript Answers

How to convert an array of key-value tuples into an object with JavaScript?

To convert an array of key-value tuples into an object with JavaScript, we use the Object.fromEntries method.

For instance, we write

const arr = [
  ["cardType", "iDEBIT"],
  ["txnAmount", "17.64"],
  ["txnId", "20181"],
];

console.log(Object.fromEntries(arr));

to call Object.fromEntries with arr to convert the arr key-value pair arrays into properties of the object returned.