如何在TypeScript中将JSON对象转换为另一个对象

时间:2019-05-01 19:50:06

标签: javascript json typescript

我想将JSON转换为特定格式,但不确定什么是最佳方法。我想做一个通用的函数。我不需要某些具有硬编码值的代码,例如rootAmount等。

我正在使用typeScriptnode

当前

{
    "elements": [
        {
            "type": "element",
            "name": "root",
            "elements": [
                {
                    "type": "element",
                    "name": "Amount",
                    "elements": [
                        {
                            "type": "text",
                            "text": "1.00"
                        }
                    ]
                },
                {
                    "type": "element",
                    "name": "Discount",
                    "elements": [
                        {
                            "type": "text",
                            "text": "0.00"
                        }
                    ]
                }
            ]
        }
    ]
}

预期:

{
  "root": {
    "Amount": "1.00",
    "Discount": "0.00"
  }
}

尝试1:。这不是整齐的方法。所以我不喜欢它。

var newJsonData = convertedXml2json
  .replace(/"elements": /g, "")
  .replace(/"type": "element",/g, "")
  .replace(/"name":/g, "")
  .replace(/"type": "text",/g, "")
  .replace(/"text":/g, "")
  .replace("[", "")
  .replace("{", "");
console.log(newJsonData);

尝试2:这是null

var len = convertedXml2json.elements,
    newData = {updatedJson:[]},
    i;

for ( i=0; i < len; i+=1 ) {
    newData.updatedJson.push(  [ convertedXml2json.elements[ i ].name, convertedXml2json.elements[ i ].elements[i].text] );
}

1 个答案:

答案 0 :(得分:3)

假设您已经将JSON解析为对象,则可以将Array.prototype.mapObject.fromEntries一起使用,将结果转换回对象:

const input = {
  "elements": [{
    "type": "element",
    "name": "root",
    "elements": [{
        "type": "element",
        "name": "Amount",
        "elements": [{
          "type": "text",
          "text": "1.00"
        }]
      },
      {
        "type": "element",
        "name": "Discount",
        "elements": [{
          "type": "text",
          "text": "0.00"
        }]
      }
    ]
  }]
};
const output = Object.fromEntries(input
  .elements.map(x => [x.name, Object.fromEntries(x
    .elements.map(y => [y.name, y.elements[0].text]))]));
console.log(output);

或者,您可以执行lodash's mapfromPairs

// import _ from 'lodash'; 

const input = {
  "elements": [{
    "type": "element",
    "name": "root",
    "elements": [{
        "type": "element",
        "name": "Amount",
        "elements": [{
          "type": "text",
          "text": "1.00"
        }]
      },
      {
        "type": "element",
        "name": "Discount",
        "elements": [{
          "type": "text",
          "text": "0.00"
        }]
      }
    ]
  }]
};
const output = _.fromPairs(
  _.map(input.elements, x => [x.name, _.fromPairs(
    _.map(x.elements, y => [y.name, y.elements[0].text]))]));
console.log(output);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>