【问题标题】:How to convert arrays in to XML in JavaScript如何在 JavaScript 中将数组转换为 XML
【发布时间】:2020-12-13 02:48:41
【问题描述】:

我有一个包含多个元素的数组:

var arrayData = [
  customerId: "123", mobileNumber: "999"},
  customerId: "122", mobileNumber: "998"},
  customerId: "121", mobileNumber: "997"}
];

我需要将其转换为如下所示的 XML:

<Result> 
    <customerId>123</customerId>
    <mobileNumber1>999</mobileNumber>
    <customerId>122</customerId>
    <mobileNumber1>998</mobileNumber>
    <customerId>121</customerId>
    <mobileNumber1>997</mobileNumber>
</Result> 

我尝试了以下方法:

arrayData.map(obj => `<Result><customerId>${obj.customerId}</customerId><mobileNumber>${obj.mobileNumber}</mobileNumber></Result>`).join('');

但我在占位符中不可用,知道如何实现这一点吗?

【问题讨论】:

    标签: javascript arrays xml multidimensional-array foreach


    【解决方案1】:

    除了您的代码无效之外,它还在工作

    var arrayData = [
      {customerId: "123", mobileNumber: "999"},
      {customerId: "122", mobileNumber: "998"},
      {customerId: "121", mobileNumber: "997"}
    ];
    
    console.log("<Result>" + arrayData.map(obj => `<customerId>${obj.customerId}</customerId><mobileNumber>${obj.mobileNumber}</mobileNumber>`).join('') + "</Result>");

    【讨论】:

      【解决方案2】:

      您不应该一遍又一遍地映射您的&lt;Result&gt;。你可以连接它

      let arrayData = [
      {customerId: "123", mobileNumber: "999"},
      {customerId: "122", mobileNumber: "998"},
      {customerId: "121", mobileNumber: "997"}
      ]
      
      
      let result = "<Result>" + arrayData.map(obj => `<customerId>${obj.customerId}</customerId><mobileNumber>${obj.mobileNumber}</mobileNumber>`).join("") + "</Result>";
      
      console.log(result);

      【讨论】:

        【解决方案3】:

        更多函数式编程方式,reduce是一个非常强大的功能。

        arrayData.reduce((acc, curr, index, src) => {    
            const customerId = `<customerId>${curr.customerId}</customerId>`
            const mobile = `<mobileNumber>${curr.mobileNumber}</mobileNumber>`
            acc = acc + `${customerId}${mobile}`    
            if(src.length - 1 === index) {
                acc = `<Result>${acc}</Result>`
            }
            return acc;
        }, '')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-10-14
          • 1970-01-01
          • 2011-09-28
          • 1970-01-01
          • 2017-05-12
          • 1970-01-01
          相关资源
          最近更新 更多