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.

Categories
JavaScript Answers

How to separate an integer into separate digits in an array in JavaScript?

To separate an integer into separate digits in an array in JavaScript, we use the split method.

For instance, we write

const n = 123456789;
const digits = n.toString().split("");

to call toString to convert n to a string.

Then we call split to split the string into the individual digit strings.

Categories
JavaScript Answers

How to store a byte array in JavaScript?

To store a byte array in JavaScript, we use the Unint8Array constructor.

For instance, we write

const array = new Uint8Array(100);
array[10] = 256;
console.log(array[10] === 0);

to create an Uint8Array array with 100 bytes.

Then we set the content of byte 11 to 256.

And then we check that its value is the same as 0, which is true since it’s 8 bits.