JavaScript将字符串转换为包含“:”的对象

时间:2019-03-21 05:46:31

标签: javascript arrays node.js dictionary

我有以下字符串var xx = "website:https://google.com";,我通常尝试使用{website:"https://google.com"}来转换为字典str.split(":"),但是这里有多个:我可以使用replace函数,但是最好的方法是什么?

2 个答案:

答案 0 :(得分:2)

const strToDictionary = kColonV => {
  const tmpArray = kColonV.split(':')
  const k = tmpArray.shift()
  const v = tmpArray.join(':')

  return {[k]:v}
}

var xx = "website:https://google.com";
strToDictionary(xx) // Object { website: "https://google.com" }

或者,也许只是:

const toDictonary = str => { return {[str.split(':')[0]]:str.substr(str.indexOf(':')+1)} }
toDictionary(xx) // Object { website: "https://google.com" }

您可以通过多种方式来表达这一点。

class Dictionary extends Object {};

const kvToDict = str => Dictionary.assign( // No need to do this, but it's interesting to explore the language.
  new Dictionary(),
  {[str.slice(0, str.indexOf(':'))]:str.slice(str.indexOf(':')+1)}
)

const kvDict = kvToDict("website:https://google.com")
console.log(kvDict.constructor, kvDict) // Dictionary(), { website: "https://google.com" }

我喜欢这个:

const kvToObj = str => Object.assign(
  {},
  {[str.slice(0, str.indexOf(':'))]:str.slice(str.indexOf(':')+1)}
)
kvToObj("website:https://google.com") // Object { website: "https://google.com" }

答案 1 :(得分:1)

您可以在第一次出现:时进行拆分。

var xx = "website:https://google.com";
xx = xx.split(/:(.+)/);
var dictionary = {[xx[0]]:xx[1]};
console.log(dictionary);