简体   繁体   中英

How to add more text with forEach inside a string?

So, I dont know if this is possible in JS, what I want to do it's something like this:

I have N objects, and want to formulate a XML with them

import config from './config'; //that actually doesent matter
//just show it here because the xml that I return have a LOT of data
//from this config

buildXML(objects) => {
 return `
   <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
   <my-xml>
     <id>${config.id}</id>
     ${objects.forEach(object) => {
       return '<object>' + object + '</object>'
     }}
   </my-xml>
 `
}

I wanted the result to me something like

  <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
   <my-xml>
     <id>42</id>
     <object> OBJECT </object>
     <object> OBJECT </object>
   </my-xml>

There's a way I can do it? Any help is welcome :) Thanks!

For instance:

return `
   <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
   <my-xml>
     <id>${config.id}</id>
     ${objects.map(object => {
       return '<object>' + object + '</object>'
     }).join('')}
   </my-xml>`;

or even shorter:

return `
   <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
   <my-xml>
     <id>${config.id}</id>
     ${objects.map(object => `<object>${object}</object>`).join('')}
   </my-xml>`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM