简体   繁体   English

将数组转换为对象的最佳方法,前缀值作为javascript中的键

[英]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.它可以用普通的 for 循环来完成,但是有没有更好的方法来使用 es6 功能以简化形式实现它。

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.如果累加器 ( acc ) 不包含键,则使用空数组创建一个。 Push the value to acc[key] after joining it by underscore.下划线加入后将值推送到acc[key]

 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 ):您可以通过使用 RegExp 仅按第一个下划线拆分来避免加入(请参阅此答案):

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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