0

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 ?

0

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.