Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript how can I use a function parameter as the key to an object?

Tags:

javascript

For example the following code prints

{ key: 'b' }

function myFunc(key, value) {
    myFunc2({key: value});
}

function myFunc2(obj) {
    console.log(obj);
}

myFunc('a', 'b');

How would I get it to print

{ 'a': 'b' }

like image 494
deltanovember Avatar asked Jun 20 '12 04:06

deltanovember


People also ask

Can you put a function in an object JavaScript?

You can call a function inside an object by declaring the function as a property on the object and invoking it, e.g. obj. sum(2, 2) . An object's property can point to a function, just like it can point to a string, number or other values. Copied!

Can we use function as a parameter in JavaScript?

Functions in the functional programming paradigm can be passed to other functions as parameters. These functions are called callbacks. Callback functions can be passed as arguments by directly passing the function's name and not involving them.

How do you use a variable as a key in an object?

You need to make the object first, then use [] to set it. var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray. push(obj);

Can a function be a key in JavaScript?

keys() is a built-in JavaScript function that returns an array of the given object's property names in the same order as we get with a standard loop. The Object. keys() method takes an object as an argument and returns the array of strings representing all the enumerable properties of a given object.


Video Answer


1 Answers

You can add properties separately from construction:

function myFunc(key, value) { 
  var item = {};
  item[key] = value;
  myFunc2(item);
}
like image 148
Alexei Levenkov Avatar answered Oct 26 '22 04:10

Alexei Levenkov