# How to solve a problem with an object?

• 0
Found this problem, how can you solve it?

Online shopping is gaining momentum every day. Of course, Mate Shop is trying to find its own niche here as well. Our robots around the clock receive calls from people from all over the world, process them and place an order. We are user friendly, so authorized users now have the opportunity to simply send SMS as a string with the number and type of products, and our robots are trained to read and understand these SMS. To be trained ... Let's write a makeOrderList function that will take an order string and return an object where the key is the product. 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, combine the words in the snake_case format. For an empty string, the function must return an empty object.

Example:

makeOrderList ('1 coca cola, 5 chicken nuggets, 20 eggs') // {coca_cola: 1, chicken_nuggets: 5, egg: 20}
JavaScript Henry Wilcox, Aug 12, 2020

• 2 Answers
• 0
``````const makeOrderList = str =>
Object.fromEntries(Array
.from(str.matchAll(/(\d+) ([^,]+)/g))
.map(n => [ n.replace(/ /g, '_'), +n ])
);``````

or

``````const makeOrderList = str => str
.split(', ')
.map(n => [ n.split(' ').slice(1).join('_'), parseInt(n) ])
.filter(n => !Number.isNaN(n))
.reduce((acc, n) => (acc[n] = n, acc), {});``````
Lilly Henson

• 0
``````const makeOrderList = str => {
const res = {}
str.replace(/(\d+)\s+(.[^\,]*)/g, (_, b, c) => {
res[c.replace(/\s/g, '_')] = +b
})
return res
}

console.log(makeOrderList('1 coca cola, 5 chicken nuggets, 20 egg'))
//{ coca_cola: 1, chicken_nuggets: 5, egg: 20 }``````

solution for integers

``````const makeOrderList = str => {
const res = {}
str.replace(/(\d*\.?\d+)\s+(.[^\,]*)/g, (_, b, c) => {
res[c.replace(/\s/g, '_')] = +b
})
return res
}

console.log(makeOrderList('1.5 coca cola, 3.5 chicken nuggets, 20 egg'))
//{ coca_cola: 1.5, chicken_nuggets: 3.5, egg: 20 }``````

fractional solution
Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!