简体   繁体   中英

Is there a way (or proposal) to return object when assigning to It, in JS?

I think, I saw it mentioned somewhere in past, but I cannot find It. So, is there way to write myObject.x = 0, myObject without comma operator?

I mainly use this with recucers:

const arr = [{key: 'width', value:15}, {key: 'height', value:30}]
const obj = arr.reduce((acc, {key, value}) => (acc[key] = value, acc), {})

I know, there is option to add a polyfill or function for that, but I'm looking for official solution (without spread ({...acc, [key]: value}) ).

I could imagine something like pascal notation obj.x:= 1 , or just make it behave like concatenation.

Maybe there is proposal for that?

You could take Object.assign which takes a target and sources and returns the target.

 const arr = [{ key: 'width', value: 15 }, { key: 'height', value: 30 }], obj = arr.reduce( (acc, { key, value }) => Object.assign(acc, { [key]: value }), {} ); console.log(obj);

Proof of keeping the same object reference of object.assign .

 const arr = [{ key: 'width', value: 15 }, { key: 'height', value: 30 }], o = {}, obj = arr.reduce( (acc, { key, value }) => Object.assign(acc, { [key]: value }), o ); console.log(o); console.log(obj);

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