簡體   English   中英

從字符串轉換為 javascript 對象的最佳方法

[英]best way to convert from string to javascript object

我有這個字符串:

periodRows.soccer.on:1,periodRows.soccer.periods:1,periodRows.soccer.prematchPeriods=1,periodRows.soccer.label:1st Half

將其轉換為該對象的最佳方法是什么?

periodRows: {
    soccer: {
      on: 1,
      periods: 1,
      prematchPeriods: 1,
      label: '1st Half',
    }
}

請注意,我不控制字符串,因此我無法更改它。

謝謝

改進的遞歸解決方案

const rec = (tokens, index, target) => {
  const prop = tokens[index];
  if (tokens.length - 1 === index) {
    const [lastProp, value] = prop.split(/[:=]/);
    target[lastProp] = value;
    return target[lastProp];
  }
  if (prop && !target[prop]) {
    target[prop] = {}; 
  }
  return target[prop];
}

"periodRows.soccer.on:1,periodRows.soccer.periods:1,periodRows.soccer.prematchPeriods=1,periodRows.soccer.label:1st Half".split(',').reduce((acc, val) => {
  const tokens = val.split('.');
  let target = acc;

  for (let i = 0; i < tokens.length; i++) {
    target = rec(tokens, i, target);
  }
  return acc;
}, {});

在此處輸入圖片說明

默認情況下,JS 無法識別字符串中的數字。 你必須明確地投射它。 你可以用這塊更新rec函數的代碼。

if (tokens.length - 1 === index) {
  const [lastProp, stringValue] = prop.split(/[:=]/);
  const parsedValue = +stringValue;
  const value = Number.isNaN(parsedValue) ? stringValue: parsedValue;
  target[lastProp] = value;
  return target[lastProp];
}

在此處輸入圖片說明

在功能上,有點短。

const f = (obj, keyPath, value) => {
    if (keyPath.length === 0) {
        return Number.isNaN(Number(value)) ? value : Number(value);
    }

    const key = keyPath[0];

    if (!obj[key]) {
        obj[key] = {};
    }

    obj[key] = f(obj[key], keyPath.slice(1), value);
    return obj;
};

const str = "periodRows.soccer.on:1,periodRows.soccer.periods:1,periodRows.soccer.prematchPeriods=1,periodRows.soccer.label:1st Half";

str.split(",")
.map(token => token.split(/[:=]/))
.map(record => ({keyPath: record[0].split("."), value: record[1]}))
.reduce((obj, item) => f(obj, item.keyPath, item.value), {});

您上面的字符串格式格式錯誤,轉換它的唯一方法是首先將其轉換為類似 json 格式的字符串,如下所示(注意類似 json 的字符串應始終用 {} 括起來) :

var periodRows = '{"soccer":{"on":1,"periods":1,"prematchPeriods":1,"label":"1st Half"}}';

然后你就可以執行轉換:

//String to Json
const str = JSON.parse(periodRows);
console.log (str);

//Json to string
var periodRows = {
    soccer: {
      on: 1,
      periods: 1,
      prematchPeriods: 1,
      label: '1st Half',
    }
}
var myStr = JSON.stringify(periodRows);
console.log (myStr);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM