简体   繁体   中英

add array of keys as property on obj as accumulator by reduce?

i have array of keys that i want to add as property with calculated val(not including on code) on empty object like this by reduce:

const f = ['a','b','c'].reduce((obj,key) => obj[key]='', {})

i was expecting the obj is the accumulator {} so i added properties that way? how do i make this work by reduce?

i was expecting and want it to result like this for that code:

{ a:'',  b:'', c:'' }

but my code only results to empty string on console. how do i achieve it?

The value that the reduce callback returns will be the accumulator in the next iteration. So, in your code, obj only refers to the object in the first iteration - on the next iteration, it refers to what obj[key] = '' resolves to, which is the empty string.

Return the object instead:

 const f = ['a', 'b', 'c'].reduce((obj, key) => { obj[key] = ''; return obj; }, {}); console.log(f); 

You could use Object.fromEntries instead, if you wanted (though, it's very new, so for good cross-browser support, include a polyfill):

 const f = Object.fromEntries( ['a', 'b', 'c'].map(key => [key, '']) ); console.log(f); 

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