简体   繁体   中英

How does "[]" work in this code snippet ? Is this a ES6 feature?

I wanted to make an array of objects from an existing array

ie [1,2,3] should become => [{1:1} , {2:1} , {3:1}]

The code below was my initial attempt but the result was [{element : 1} , {element : 1}, {element : 1}]

let scores = [1,2,3];
let sr = [];
scores.forEach(element => {
    sr.push({ element : 1 });
});

I put square brackets around "element" and to my surprise it worked.

let scores = [1,2,3];
let sr = [];
scores.forEach(element => {
    sr.push({ [element] : 1 }); // this works but I have no clue how :(
});

I am sorry to have worded this question vaguely but I wanted to know the reason behind it badly.

This is done when you want to set a dynamic key . I suggest to use .map :

 const scores = [1,2,3]; const sr = scores.map( element => ({ [element] : 1 }) ); console.log(sr);

so [] in that context resolves as an expression (which was always weird to me that it wasn't () inside object property names to resolve as an expression...), but yeah, it's assigning the value of the var to the key instead of directly defining the key as 'element' (the default). it's ES6 syntax, and I don't think it has a name exactly...

let sr = scores.map(element => ({ [element] : 1 }));

is also faster for what you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM