convert an array of variable names into strings js [duplicate] - javascript

This question already has answers here:
Variable name as a string in Javascript
(20 answers)
Closed 4 years ago.
var a = "aa", b= "bb",c ="cc", d="dd", e="ee";
array = [a,b,c,d,e] // outputs ["aa", "bb", "cc", "dd", "ee"];
However is there a possibility in javascript to convert the variables (a, b,c,d,e) into strings?
Like: "a", "b", "c", "d", "e"??
P.S: the array values could be dynamic as well or more than the length mentioned above.
Thanks for the help!!

You could do this with ES6 shorthand property names and return array of strings.
let a = "aa", b= "bb",c ="cc", d="dd", e="ee";
let strings = Object.keys({a, b, c, d, e});
console.log(...strings)

Something like this
var a = "aa", b= "bb",c ="cc", d="dd", e="ee";
var array = [a,b,c,d,e];
({a,b,c,d,e} = array)
var keys = Object.keys({a,b,c,d,e});
console.log(keys)
console.log(array)

Related

Append string to Array in non-mutative way in Javascript

I have function that returns a string or an array of strings depending on some rules defined inside.
So we want to basically take that String/Array and basically make sure that we end up with an array of strings with an additional string 'X' added as last item to that array.
concat is a very useful array method for that purpose, since it both accepts an array as argument or a non-array. Either way it will concatenate those/that value(s) to the array on which it is called, and return the result.
In addition, concat accepts more than one argument, so you can at the same time add some other value, like "X":
function f(b) {
if (b) return ["a", "b"];
else return "a";
}
// call f twice, the first time it returns "a", the second time ["a", "b"]
for (let b = 0; b < 2; b++) {
let res = [].concat(f(b), "X");
console.log(res);
}
function append(vec, word){
if (typeof(vec)==="string"){
vec = [vec]
}
return vec.concat(word)
}
a = "foo"
b = ["foo","bar"]
append(a,"xyz") //-> [ 'foo', 'xyz' ]
append(b,"xyz") //-> [ 'foo', 'bar', 'xyz' ]
When you're dealing with a variable that may or may not already be an array, the .flat() method comes in handy, so you can wrap it in an array and then make sure the array is only one level deep.
This is how I would achieve this, and there are two different ways you could write up this function, so I'll include both below:
const stringExample = "test";
const arrayExample = ["1", "2", "3"];
const xStrings1 = strings => [...[strings].flat(), "X"]; // option 1
const xStrings2 = strings => [strings, "X"].flat(Infinity); // option 2
console.log(xStrings1(stringExample)); // -> ["test", "X"]
console.log(xStrings2(stringExample)); // -> ["test", "X"]
console.log(xStrings1(arrayExample)); // -> ["1", "2", "3", "X"]
console.log(xStrings2(arrayExample)); // -> ["1", "2", "3", "X"]
I've benchmark-tested both functions with both examples of sample data, and they are nearly identical in performance for both types. Neither is conclusively faster than the other, so it's up to you which you would prefer to use.

Is there a way to add multiple properties into an object? [duplicate]

This question already has answers here:
How do I merge two dictionaries in Javascript? [duplicate]
(4 answers)
ECMAScript object spread/rest - assigning to multiple properties at once
(2 answers)
Closed 2 years ago.
For example given
const a = {
"a": 1,
"b": "hi",
}
const c = "54"
const d = "66"
I want a to be
a = {
"a": 1,
"b": "hi",
"c": 54,
"d": 66,
}
I want to do it in a single line so
a = {c, d}
But the above code will get rid of a, b. Any quick way to accomplish this?
Spread syntax
const a = {
a: 1,
b: 'hi',
};
const c = '54';
const d = '66';
console.log({ ...a, c, d });
One way is to use Object.assign:
a = Object.assign({}, a, { c, d });
This effectively creates a new object ({}), then it copies all properties from your initial object (a) then it copies the new properties ({c, d }).

destructure object in javascript es6 when keys are integers [duplicate]

This question already has answers here:
Object destructuring with property names that are not valid variable names
(2 answers)
Closed 6 years ago.
When we have an object in JS like
var obj = {a: "apple", p: "pen"};
then we can destructure it as follows
var {a, p} = obj; /* a = 'apple', p = 'pen' */
i want to know in case when keys are integers, how can we destructure it ? since we cannot declare integers as variable name
var obj = {0: 'pineapple', 1: 'pen'};
Just like any other assigning to new variable names
var {0:a, 1:b} = obj;

How do I compare two arrays in nodejs [duplicate]

This question already has answers here:
How to compare two arrays in node js?
(8 answers)
Closed 8 years ago.
Say I have two arrays
["a", "b", "c"]
["c", "a", "b"]
What is the best way to compare these two arrays and see if they are equal (they should come as equal for the above scenario)
function compareArrays(array1, array2) {
array1 = array1.slice();
array2 = array2.slice();
if (array1.length === array2.length) { // Check if the lengths are same
array1.sort();
array2.sort(); // Sort both the arrays
return array1.every(function(item, index) {
return item === array2[index]; // Check elements at every index
}); // are the same
}
return false;
}
console.assert(compareArrays(["a", "b", "c"], ["c", "a", "b"]) === true);
You can try with _.difference
var diff = _(array1).difference(array2);
if(diff.length > 0) {
// There is a difference
}
this will not work because different returns diff from first array.
_.difference(['a'] ,['a','b']) is 0 but two array is not equal.

How do I make a copy of a JavaScript object? [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Closed 8 years ago.
I need to make a temporary copy of a variable to make changes to. Here's what I mean:
var x = ["a", "b", "c"];
var y = x;
y[1] = "2"
//x: ["a", "b", "c"];
//y: ["a", 2, "c"];
It's worth pointing out that I'm using an object I defined myself, and not a built in data structure.
The standard method for 'cloning' array of primitive types in JavaScript (based on your requirements) is shown below:
var x = ["a", "b", "c"];
var y = x.slice(0);
y[1] = "2";
Be aware, that if array contains complex types (objects), then it will keep original references; in other words, it does not perform 'deep' copy on array of objects.
Try this
var x = ["a", "b", "c"];
var y = JSON.parse(JSON.stringify(x));
//y = ["a", "b", "c"];
Then u can manipulate your new object as u want.
You can use jQuery to clone your object
var newObject = jQuery.extend(true, {}, oldObject);
jQuery Documentation

Categories