javascript equivalent to [x for x in array]

Viewed 183

Is there any operation in Javascript just like [x for x in array] in python?

For example, I'm using javascript to reading a json file where there're dozens of (key, value) pairs needed to be handled(or transformed into other format). And I thought working in this way is stupid:

let transformed = []
for (let key in json){
   transformed = [ /* doing some transform*/ ]
}

Is there anything like:

let transformed = [
 lambda function1(key), lambda function2(value) for key, value in json
]

Thanks in advance.

4 Answers

The rough equivalent of Python's list comprehension is Array.map:

const myArray = [1, 2, 3]
const transformed = myArray.map((item) => item + 1)
// [2, 3, 4]

But your example is not about an array, but about an Object with keys and values. In Python, this would be a dict, and you'd use a dict comprehension along the lines of {function1(key): function2(value) for key, value in my_dict.items()}.

In JavaScript, you can turn such an object into an array with Object.entries, then perform the map, and finally transform it back into an object using Object.fromEntries:

const myObject = { a: 1, b: 2 }
const transformed = Object.fromEntries(Object.entries(myObject)
    .map(([key, value]) => [key + 'x', value + 1]))
// { ax: 2, bx: 3 }

Note that fromEntries is fairly new and you might need to add a polyfill for it.

You can use a code likes this. You must use a function that handle operation on current single item.

const words = ['hello', 'bird', 'table', 'football', 'pipe', 'code'];
const capWords = words.forEach(capitalize);

function capitalize(word, index, arr) {
  arr[index] = word[0].toUpperCase() + word.substring(1);
}
console.log(words);
// Expected output:
// ["Hello", "Bird", "Table", "Football", "Pipe", "Code"]

First of all, javascript does NOT support Associative Arrays. If you are used to them in Python, PHP, and other languages you need to do a little workaround in JS to achieve the same functionality.

The most common way to simulate an associative array is using an object.

let testObject = {name: "Color", value: "Red"};

And then you push every object into an array so you end up with something like this:

let testArray = [{name: "Color", value: "Red"}, {name: "Color", value: "Blue"}];

Once you have this array consisting of objects, you can use map function to go through every object in the array and do whatever you want with it.

testArray.map((item, index) => {
 console.log("The value of "+index+". item is: "item.value);
})

You can use Array.map() function. It work pretty like Array.forEach() function

const numbers = [1, 2, 3, 4, 5]

let newArray = numbers.map((element) => {
    return element * 2
})

console.log(newArray) // excepted : [ 2, 4, 6, 8, 10 ]

It can be reduce using

const numbers = [1, 2, 3, 4, 5]

let newArray = numbers.map(element => element * 2)

console.log(newArray) // excepted : [ 2, 4, 6, 8, 10 ]

For more informations, you can this documentation https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Related