create an array based on a variables string [duplicate] - javascript

This question already has answers here:
Convert string to variable name in JavaScript
(11 answers)
Closed 8 years ago.
I want to pass a string for an array's name to a function, and the function create that array, e.g:
make_array('array_name', data);
function make_array(array_name, data){
array_name = [];
// do stuff
array_name.push(//stuff);
}
I don't want to have to create the array first manually

You can do .
window[array_name] = [];

You can use eval() to do it.
eval("var " + array_name + " = []");

If you just want the function to return an array, there is no need to create it beforehand. You can just do this:
function make_array(data){
var array_name = [];
// do stuff
array_name.push(//stuff);
return array_name;
}
var my_new_array = make_array(data);

Related

Unable to bind javascript variable to JSON object key [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 4 months ago.
I am trying to add a value in place of json object key but it always returns variable name.
My Code:
var projectName='';
let tempArray=[];
let output={};
for(i=0;i<myJsonArray.length;i++){
name = myJsonArray[i].Project;
tempArray.push(myJsonArray[i]);
}
output= {projectName :tempArray};
console.log(JSON.stringify(output));
This returns a JSON as
{"projectName":[{"Day":"MON","Project":"ABC","Billing Rate":"xxx"},{"Day":"TUE","Project":"ABC","Billing Rate":"xyx"}]}
But I need something like this:
{"ABC":[{"Day":"MON","Project":"ABC","Billing Rate":"xxx"},{"Day":"TUE","Project":"ABC","Billing Rate":"xyx"}]}
Can someone help on what I am missing here.
Kind Regards.
You should wrap the project name into [] that would help to make a value become a key
var name = '';
let tempArray = [];
let output = {};
for (i = 0; i < myJsonArray.length; i++) {
name = myJsonArray[i].Project;
tempArray.push(myJsonArray[i]);
}
output = {
[name]: tempArray
};
console.log(JSON.stringify(output));
P/s: I don't see any projectName variable there, so I replace it by name instead.

Check if value exists in array javascript [duplicate]

This question already has answers here:
Object comparison in JavaScript [duplicate]
(10 answers)
How to determine equality for two JavaScript objects?
(82 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 3 years ago.
I have this data
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
I want to check if my new data is already exists in that array. I'm trying to use includes()
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
Then i try another way
function inArrayCheck(val) {
if (Object.values(selectedValue).indexOf(val) > -1) {
console.log(val);
}
}
both of them returning false when i input Data A
Objects will not be equal unless they have the same reference, even when they have the same key/value pairs. You can do the comparison after converting the objects to string using JSON.stringify with limited capability, like the order of elements in the object and the case of strings matters:
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
function inArrayCheck(val) {
return selectedValue.some(obj => JSON.stringify(obj) === JSON.stringify(val))
}
console.log(inArrayCheck({0:'Data A'}))
You are trying to find a value from an object which is inside an array. You can try like so:
var selectedValue = []; // this is an array
selectedValue.push({0:'Data A'}); // here you push an object to the array
selectedValue.push({1:'Data B'}); // to find the value later you need to find it inside the object!
// above three lines can also be written like so and are the same
// var selectedvalue1 = [{0:'Data A'}, {1:'Data B'}];
function inArrayCheck(val) {
selectedValue.forEach(function(element){
if (Object.values(element).indexOf(val) > -1) {
console.log('found value: ' + val);
}
});
}
inArrayCheck('Data A');
if you want to use includes you need to have an array like so:
var selectedValue = [];
selectedValue.push('Data A');
selectedValue.push('Data B');
// above three lines can also be written like so and are the same
// var selectedvalue1 = ['Data A', 'Data B'];
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
inArrayCheck('Data A')
You forgot to go trough each value. You can also use find() function, to check if array have a value which sutisfy your condition.

Pass an string representing an object function as callback [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 5 years ago.
This code doesn't work:
var my = {
testFunction: function(text) {
alert(text);
}
};
var functionName = "my.testFunction";
var f = window[functionName];
f('yeha');
Any idea why?
Update:
I don't know in advance the functionName. It might be 'my.testFunction' or 'my.test.another.function' etc.
I'm writing a validation handler and all my js will know is a string representing a function that could be a function inside an object.
This should work.
var my = {
testFunction: function(text) {
alert(text);
}
};
// the string can't be evaluated as nested object hierarchy.
// split it to address the several nodes and properties
var functionName = "my.testFunction".split('.');
var f = window[functionName[0]][functionName[1]];
f('yeha');

How to grab array of string represented parameters in JavaScript [duplicate]

This question already has answers here:
How to get function parameter names/values dynamically?
(34 answers)
Closed 6 years ago.
I'm trying to grab an array of string represented parameters from a function and I'm unsure how to proceed. Basically given the function below
function MyFunc(param1, param2, param3){
//do all the things
}
What would the function "getParams" look like to do the following
getParams(MyFunc) // ["param1","param2","param3"]
This is a bit messy, but you can do this by converting your function to a string and then splitting it until you get just the parameters:
var getFuncParams = function(MyFunc) {
var str = MyFunc.toString()
var strParams = str.substr((str.indexOf('(')+1), (str.indexOf(')') - str.indexOf('(')) - 1)
var params = strParams.split(",")
return params;
}

How can I convert a string to a variable name in Node.js? [duplicate]

This question already has answers here:
Use variable's value as variable in javascript
(2 answers)
Closed 8 years ago.
//Admin.js
var insertAdminFeed = function(s, id, timestamp){
var admin_att_new_key = '12345';
var admin_att_new_key2 = 'abc';
var admin_att_new_key3 = 'zyzyz';
var s = 'admin_att_new_key';
console.log(global[s]); //should print '12345'
};
exports.insertAdminFeed = insertAdminFeed;
I want to convert a string to a variable in node.js (I have many keys, and I don't want to write if/else statements for all of them) How can I do that?
This is not really possible in JavaScript.
You'd usually use an object literal to achieve similar needs.
var key = 'foo';
obj[key] = 1;
obj['foo'];
To be thorough, it is technically possible in JS using eval. But really, don't do this.
eval("var "+ name + " = 'some value';");
eval("console.log("+ name +")");

Categories

Resources