Javascript 将对象的值从字符串转换为数字
我当前正在尝试将此URL转换为对象: 培根=0,奶酪=0,肉=0,沙拉=1 就我所知:Javascript 将对象的值从字符串转换为数字,javascript,reactjs,object,url,react-router,Javascript,Reactjs,Object,Url,React Router,我当前正在尝试将此URL转换为对象: 培根=0,奶酪=0,肉=0,沙拉=1 就我所知: const urlParams = new URLSearchParams(props.match.params.ingredients); const entries = urlParams.entries(); const params = Object.fromEntries(entries); 我现在有这个: {培根:“0”,奶酪:“0”,肉:“0”,沙拉:“1”} 我需要将这些值转换成数字 我尝试
const urlParams = new URLSearchParams(props.match.params.ingredients);
const entries = urlParams.entries();
const params = Object.fromEntries(entries);
我现在有这个:
{培根:“0”,奶酪:“0”,肉:“0”,沙拉:“1”}
我需要将这些值转换成数字
我尝试过使用循环并迭代Number()和parseInt(),但我就是想不出来。在传递到
fromEntries
之前,将每个值映射到一个数字:
const urlParams = new URLSearchParams(props.match.params.ingredients);
const entries = [...urlParams.entries()];
const entriesNumeric = entries.map(([key, value]) => ([key, Number(value)]));
const params = Object.fromEntries(entriesNumeric);
将每个值映射到一个数字,然后再从Entries传递到
:
const urlParams = new URLSearchParams(props.match.params.ingredients);
const entries = [...urlParams.entries()];
const entriesNumeric = entries.map(([key, value]) => ([key, Number(value)]));
const params = Object.fromEntries(entriesNumeric);
我得到这个错误:TypeError:entries.map不是一个函数。我已经尝试过很多次了。看起来像fromEntries
可以接受任何iterable,而不仅仅是数组-只需先将entries()
迭代器转换为数组对不起,我不确定你的意思。entries()
返回迭代器,所以你只需要将它转换为数组。完美的非常感谢。我得到这个错误:TypeError:entries.map不是一个函数。我已经尝试过很多次了。看起来像fromEntries
可以接受任何iterable,而不仅仅是数组-只需先将entries()
迭代器转换为数组对不起,我不确定你的意思。entries()
返回迭代器,所以你只需要将它转换为数组。完美的非常感谢。