我需要帮助将给定的字符串拆分为双冒号作为分隔符,并希望将其转换为键值对。(注意:最后一项将是分隔符)
var str = "Name::jignesh::Age::34::pageName::home::device::tablet::";
需要输出:
{
Name:jignesh,
Age:34,
pageName: home,
device: tablet
}
我尝试使用 str.split('::') 拆分它,输出为:
Array(9) [ "Name", "jignesh", "Age", "34", "pageName", "home", "device", "tablet", "" ]
任何人都可以请指导。
谢谢,吉格尼什
试试这个:
const str = "Name::jignesh::Age::34::pageName::home::device::tablet::";
const dictionary = str.split('::').reduce((accumulator, key, i, array) => {
// in case the current key's index is an
// even value AND it is not an empty string
return i % 2 === 0 && key
// include the "key: value" pair into the dictionary
? {...accumulator, [key]: array[i + 1]}
// else - continue
: accumulator;
}, {});
console.log(dictionary);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句