简体   繁体   中英

best way to convert array to object with prefix value as key in javascript

I have an array with prefix values

["options_a",
"options_b",
"options_c",
"capable_d",
"capable_e_c"
]

i need the output to be in object format with prefix as key and grouped split string as value

object output format needed
{
"options":["a","b","c"],
"capable":["d","e_c"]
}

it can be done with normal for loop, but is there better way of achieving it with simplified form using es6 functionality.

Thank you.

Reduce the array of the prefixed values. Split the item by underscore ( _ ), and use destructuring to get the key, and an array of value (the value might have multiple items after splitting by underscore). If the accumulator ( acc ) doesn't contain the key, create one with an empty array. Push the value to acc[key] after joining it by underscore.

 const arr = ["options_a","options_b","options_c","capable_d","capable_e_c"] const result = arr.reduce((acc, item) => { const [key, ...value] = item.split('_') if(!acc[key]) acc[key] = [] acc[key].push(value.join('_')) return acc; }, {}) console.log(result)

You can avoid the need to join by using a RegExp to split only by the 1st underscore (see this answer ):

 const arr = ["options_a","options_b","options_c","capable_d","capable_e_c"] const result = arr.reduce((acc, item) => { const [key, value] = item.split(/_(.+)/) if(!acc[key]) acc[key] = [] acc[key].push(value) return acc; }, {}) console.log(result)

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