简体   繁体   English

如何将 object 中带逗号的单词转换为值

[英]How convert words with comma in object with value

I have:我有:

WAIT_FOR_ANALYSIS,EMAIL_SENT WAIT_FOR_ANALYSIS,EMAIL_SENT

and I need transform it to:我需要将其转换为:

[{ value: 'WAIT_FOR_ANALYSIS' }, { value: 'EMAIL_SENT' }]

I tried:我试过了:

const wordToArray = filtered.split(',');
console.log(Object.assign({}, wordToArray));

But returns:但返回:

{0: "WAIT_FOR_ANALYSIS", 1: "EMAIL_SENT"}

What your code does is splitting your input string, using comma as a delimiter (which would result in ['WAIT_FOR_ANALYSIS', 'EMAIL_SENT'] ), after that you do Object.assign({}, wordToArray) which takes your array (which is essentially an object) and assigns key-value pairs (indexes and respective strings) to the empty object, giving you above result.您的代码所做的是拆分您的输入字符串,使用逗号作为分隔符(这将导致['WAIT_FOR_ANALYSIS', 'EMAIL_SENT'] ),然后您执行Object.assign({}, wordToArray)获取您的数组(其中本质上是一个对象)并将键值对(索引和相应的字符串)分配给空的 object,从而为您提供上述结果。

What you need to do instead is mapping your array (with Array.prototype.reduce() ) into array of the same size where each string value is mapped into an object {value: ..} .您需要做的是将您的数组(使用Array.prototype.reduce() )映射到相同大小的数组中,其中每个字符串值都映射到 object {value: ..}

With slight trick of destructuring it may look as follows:通过轻微的解构技巧,它可能如下所示:

 const str =`WAIT_FOR_ANALYSIS,EMAIL_SENT`, result = str.split(',').map(value => ({value})) console.log(result)
 .as-console-wrapper{min-height:100%;}

As Yevgen mentioned, you can map each token (following the split operation) to an object.正如 Yevgen 所提到的,您可以将 map 每个令牌(在拆分操作之后)转换为 object。 Instead of creating objects with key/value pairs, you can use the ECMAScript 2015 shorthand notation , as seen in his example.您可以使用ECMAScript 2015 速记表示法,而不是使用键/值对创建对象,如他的示例所示。

When mapping to a object, if you simply pass-in the reference to another variable.当映射到 object 时,如果您只是传入对另一个变量的引用。 A key will be created based on the name of the variable.将根据变量的名称创建一个键。

 const str = 'WAIT_FOR_ANALYSIS,EMAIL_SENT' const arr = str.split(',').map(value => ({ value })) // { value: value } console.log(arr)
 .as-console-wrapper { top: 0; max-height: 100%;important; }

Here is an advanced solution, where an enum-like object is created.这是一个高级解决方案,其中创建了类似枚举的 object。

 const str = 'WAIT_FOR_ANALYSIS,EMAIL_SENT' const main = () => { const statusType = createEnum(str.split(/\s*,\s*/g)) console.log(statusType) } const createEnum = (values) => values.reduce((res, name, ordinal) => ({...res, [name]: { name, ordinal } }), {}) main()
 .as-console-wrapper { top: 0; max-height: 100%;important; }

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

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