简体   繁体   English

在将对象数组转换为 xml 时,如何分别摆脱由数组键包裹的每个元素?

[英]How can I get rid of each element wrapped by the array key separately while converting array of object to xml?

While converting an array of object into xml, each element inside the array gets wrapped with the array key in the xml.在将对象数组转换为 xml 时,数组中的每个元素都被 xml 中的数组键包裹。 How can I make all element wrapped by the array key for once?如何使数组键包裹的所有元素一次?

the problem is for each element in the array gets wrapped by the array key separately while converting the xml.问题是数组中的每个元素在转换 xml 时分别由数组键包装。

my json is like:我的 json 是这样的:

  {a: 
      [
       {first: 1}, 
       {second:2}
      ] 
  }

this gets converted to这被转换为

    <a>
      <first> </first>
    </a>
    <a>
      <second> </second>
    </a>   

but what I want is但我想要的是

    <a>
       <first> </first>
       <second> </second>
    </a>

I found a solution.我找到了解决方案。

function OBJtoXML(obj) {
  var xml = '';
  for (var prop in obj) {
    xml += obj[prop] instanceof Array ? '' : "<" + prop + ">";
    if (obj[prop] instanceof Array) {
      xml += "<" + prop + ">";
      for (var array in obj[prop]) {
        xml += OBJtoXML(new Object(obj[prop][array]));
      }
      xml += "</" + prop + ">";
    } else if (typeof obj[prop] == "object") {
      xml += OBJtoXML(new Object(obj[prop]));
    } else {
      xml += obj[prop];
    }
    xml += obj[prop] instanceof Array ? '' : "</" + prop + ">";
  }
  var xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
  return xml
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从网页获取JSON对象数组并将每个元素添加到HTML中的行? - How can i get an array of JSON object from a webpage and add each element to the row in HTML? 如何循环遍历 object 并获取每个元素的索引并将其存储在数组中? - How can I loop through an object and get the index of each element and store it in an array? JS:如何在数组中使用一个元素然后摆脱它 - JS: How do I use an element in an array and then get rid of it 如何为数组中另一个数组中的对象中的每个对象分配唯一键和线性键? - How can I assign unique and linear key for each object within an array that's in an object within another array? 如何获取数组中对象的键? - How can i get the key of Object inside Array? 如何获取 object 中数组元素的索引? - How can I get the index of array element inside object? 如何向对象添加数组,但是为每个数组元素过滤除了一列以外的所有数组? - How can I add an array to an object but filter out all but one column for each array element? 如何处理此JSON数组,以删除数组的每个元素中的包装器对象? 使用JavaScript - How can I process this JSON array to remove a wrapper object in each element of the array? using JavaScript 如何在Json Array中获取值并分别使用它们 - How to get values in Json Array and use each of them separately 如何在点击时分别为每个元素设置动画? - How can I animate each element separately on click?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM