0

I am manipulating string to display in UI, Data is being dynamically with below code sometime i don't get header and details so how to make IHeader and IResponse optional for the string concatenation below.

if i dont have IHeader it will break at IHeader.id and throw exception i want to display whatever data is available to render.

main.js

const data = [{
    id: "header",
    name: "IHeader"
}, {
    id: "param",
    name: "IParams"
}, {
    id: "details",
    name: "IResponse"
}]

function buildText(data) {
    var IParams;
    var IResponse;
    var IHeader;
    for (var item of data) {
        if (item.id === "param") {
            IParams = item;
        } else if (item.id === "header") {
            IHeader = item;
        } else if (item.id === "details") {
            IResponse = item;
        }
    }
    var text = '';
    text += app + '.setConfig({\n' + "env:" + getEnv() + '\n});' + '\n\n';
    text += 'let param:' + IParams.name + ' ' + '=' + '' + JSON.stringify(request, null, 4) + ';\n\n';
    text += ref + '(' + 'param,(result:' + ' ' + '{' + '\n' + IHeader.id + ':' + IHeader.name + '\n' + IResponse.id + ':' + IResponse.name + '\n' + '})' + ' ' +
        ' => {\n  console.log(result); \n});';

}
aftab
  • 693
  • 1
  • 12
  • 27
  • 1
    so build the string inside the ifs instead of setting variables.... – epascarello Sep 27 '19 at 14:32
  • 1
    Use object and [bracket notation](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – User863 Sep 27 '19 at 14:34
  • @User863 i tried IHeader[id] or IHeader["id"] both didn't work it still throws id is undefined – aftab Sep 27 '19 at 14:41

1 Answers1

0

1 - You can try to create an object with empty values. That'll prevent the exception.

   emptyObject = {id: ""} // more empty keys, if there is
   IParam = (item.id === "param") ? item : emptyObject

2 - Or ignore that concatenation of the variable if undefined or null.

if (Iparam) {
    // concatenation ..
}
Anna
  • 319
  • 5
  • 18