简体   繁体   English

如何使用 javascript 将字符串转换为 object 并在 snake_case 中返回一些键?

[英]How to convert a string into an object with javascript and return some keys in snake_case?

So I'm trying to to write a function, which takes an order as a string, and converts it into an object where the product will be the key.所以我正在尝试编写一个 function,它将订单作为字符串,并将其转换为 object,其中产品将是关键。 And the key value is the number of the ordered product in numerical form.键值是数字形式的订购产品的数量。 Each item in an order always starts with the quantity of the product.订单中的每个项目始终以产品的数量开始。

If the product name consists of more than one word, function has to combine the words in the snake_case format.如果产品名称包含多个单词,function 必须以snake_case 格式组合单词。 For an empty string, the function must return an empty object.对于空字符串,function 必须返回一个空的 object。

Can someone explain the best way to do this function?有人可以解释执行此 function 的最佳方法吗?

For example:例如:

myOrder('2 coca cola, 4 beer) // {coca_cola: 2, beer: 4}

You can use map and reduce :您可以使用mapreduce

 function myOrder(str) { return str.length === 0? {}: str.split(',').map(s => s.match(/(?<qty>\d+)\s*(?<name>.+)/).groups).reduce((res, {name, qty}) => ({...res, [name.replace(/\s/g, '_')]: +qty }), {}); } console.log( myOrder('') ); console.log( myOrder('2 coca cola, 4 beer') ); console.log( myOrder(' 46 foos & bars, 0fizz') );

So i think i'll first split the string using the comma as divider, after that i'll have an array with an entry for each item.所以我想我会首先使用逗号作为分隔符分割字符串,然后我将有一个数组,其中每个项目都有一个条目。

After that i'll split it again using space as divider and get an array where the first element is the quantity and the others are the name of the item.之后,我将使用空格作为分隔符再次拆分它并获得一个数组,其中第一个元素是数量,其他元素是项目的名称。

From here you can build up the object you need:)从这里您可以构建您需要的 object :)

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

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