Mar1009
Mar1009

Reputation: 811

How to convert arrays in to XML in JavaScript

I have a array with multiple elements in it :

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

I need this to convert into XML like below:

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

I've tried the following:

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

but I'm getting unavailable in placeholders , any idea how to achieve this ?

Upvotes: 0

Views: 163

Answers (3)

Hamza Zaidi
Hamza Zaidi

Reputation: 672

More functional programming approach, reduce is a very powerful function.

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;
}, '')

Upvotes: 1

Saadi Toumi Fouad
Saadi Toumi Fouad

Reputation: 2829

Here is it working, besides you have invalid code

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>");

Upvotes: 1

Ilijanovic
Ilijanovic

Reputation: 14904

You should not map your <Result> over and over again. You can concat it

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);

Upvotes: 1

Related Questions