【问题标题】:JavaScript convert string to object contains ":"JavaScript 将字符串转换为对象包含“:”
【发布时间】:2019-03-21 05:46:31
【问题描述】:

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

【问题讨论】:

  • {website:https://google.com} 语法无效...
  • JavaScript 没有字典,它们被称为 objects
  • 你的意思是你想得到{website: "https://google.com"}

标签: javascript arrays node.js dictionary


【解决方案1】:
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" }

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      • 1970-01-01
      相关资源
      最近更新 更多