Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-like unpacking in JavaScript

I have the following string

output_string = "[10, 10, [1,2,3,4,5], [10,20,30,40,50]]"

Then I JSON.parse it

my_args = JSON.parse(output_string)

How do I unpack it in a Python-like way so that every element in my_args becomes an argument to a JavaScript function?

some_javascript_function(*my_args)
// should be equivalent to:
some_javascript_function(my_args[0],my_args[1],my_args[2],my_args[3])
// or:
some_javascript_function(10, 10, [1,2,3,4,5], [10,20,30,40,50])

Is there a core JavaScript idiom that does that?

like image 294
Kit Avatar asked Aug 16 '11 11:08

Kit


People also ask

What is unpacking in Python?

Introduction. Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .

Can lists be unpacked in Python?

We can use * to unpack the list so that all elements of it can be passed as different parameters.


3 Answers

Once you 've collected the function arguments in an array, you can use the apply() method of the function object to invoke your predefined function with it:

   some_javascript_function.apply(this, my_args) 

The first parameter (this) sets the context of the invoked function.

like image 70
fbuchinger Avatar answered Sep 30 '22 08:09

fbuchinger


You can achieve that by doing this some_javascript_function(...my_args)

This is called spread operation (as unpacking is in python). view docs here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator

like image 35
ifedapo olarewaju Avatar answered Sep 30 '22 09:09

ifedapo olarewaju


Unpack using "..."

The same way you accept unlimited args, you can unpack them.

let vals = [1, 2, 'a', 'b'];

console.log(vals);    // [1, 2, "a", "b"]
console.log(...vals); // 1 2 "a" "b"

Example: Accept unlimited arguments into a function

It will become an array

const someFunc = (...args) => {
    console.log(args);    // [1, 2, "a", "b"]
    console.log(args[0]); // 1
    console.log(...args); // 1 2 "a" "b"
}

someFunc(1, 2, 'a', 'b');

Example: Send array of arguments into a function

const someFunc = (num1, num2, letter1, letter2) => {
    console.log(num1);    // 1
    console.log(letter1); // "a"
}

let vals = [1, 2, 'a', 'b'];
someFunc(...vals);

Send arguments

like image 20
joshuakcockrell Avatar answered Sep 30 '22 08:09

joshuakcockrell