I have a array of variables. I'd like to get a string of all the variables with their variables name and the value it represents. Here is what I have.
var date = '1/1/22';
var time = '5:00'
var name = 'some name';
var number = '123-456-7890';
var arr = [date,time,name,number]
I'd like to turn it into a string maybe like this:
var text = '';
text = arr[0].toUpperCase() ": " arr[0] "\n";
which would make text output like this in a email body
date: 1/1/22
time: 5:00
name: some name
number: 123-456-7890
CodePudding user response:
This can not be done with an array because array items do not have names. The variable names are not kept when constructing the array, only their values.
It can be done with an object, and then you can use Object.entries to iterate over the contents of the object and get both the key and the value for each item:
var date = '1/1/22';
var time = '5:00'
var name = 'some name';
var number = '123-456-7890';
var obj = { date, time, name, number };
for (var [key, value] of Object.entries(obj))
console.log(key ": " value)
A final note: the ordering of items as returned by Object.entries() is not guaranteed.
Another option is to put objects with a single named property into an array. This way the ordering of items is guaranteed, and item names are available using Object.keys():
var date = '1/1/22';
var time = '5:00'
var name = 'some name';
var number = '123-456-7890';
var arr = [ { date }, { time }, { name }, { number } ];
for (var item of arr) {
// We have knowledge that every object has only 1 property, get its name:
var key = Object.keys(item)[0];
console.log(key ": " item[key]);
}
CodePudding user response:
I think your best option is to use a 2-dimensional array. Here is a code snippet (I copied this from a MacBook, so hopefully it formats ok):
function getVarAndValArray() {
var date = '1/1/22';
var time = '5:00'
var name = 'some name';
var number = '123-456-7890';
//Create two-dimensional array
let arr = [];
arr[0] = []; //date
arr[1] = []; //time
arr[2] = []; //name
arr[3] = []; //number
//-----------------------------------
//Insert variables names and values
//Date
arr[0][0] = 'date'; //variable
arr[0][1] = '1/1/22'; //value
//Time
arr[1][0] = 'time'; //variable
arr[1][1] = '5:00'; //value
//Name
arr[2][0] = 'name'; //variable
arr[2][1] = 'some name'; //value
//Number
arr[3][0] = 'number'; //variable
arr[3][1] = '123-456-7890'; //value
//------------------------------------
return arr;
}
//Output the results
var arr = getVarAndValArray();
var text = '';
text = arr[0][0].toUpperCase() ": " arr[0][1] "\n";
text = arr[1][0].toUpperCase() ": " arr[1][1] "\n";
text = arr[2][0].toUpperCase() ": " arr[2][1] "\n";
text = arr[3][0].toUpperCase() ": " arr[3][1] "\n";
alert(text);
