Home > other >  Creating custom dynamic JSON string
Creating custom dynamic JSON string

Time:10-18

I am trying to achieve the following dynamic JSON string creation. I can produce the id part but don't how to produce the name part. Ids are from the list and name is from the textbox.

I tried a lot but nothing seems to work. I want to select both strings and text box should result as below.

{
  "name": "GROUP-X1",
  "objects": [{ // this part is needed as a complete string
    "type": "Host",
    "id": "0050569A-7800-0ed3-0000-008589948757"
  }, {
    "type": "Host",
    "id": "0050569A-7800-0ed3-0000-008589945523"
  }]
}

var output = createJSON1();

function createJSON1() {
  var arr = $("#select1 > option").map((index, val) => ({
    "type": "Host",
    id: val.value
  })).get();
  return JSON.stringify(arr);
}

console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="text" id="srch-obj" value="GROUP-X1">
<select id="select1" multiple size="2" style="width: 480px">
  <option>0050569A-7800-0ed3-0000-008589948757</option>
  <option>0050569A-7800-0ed3-0000-008589945523</option>
</select>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Your code already builds the objects array. As such, all you need to do is wrap the output within another object providing the name property which you can retrieve from the value of #srch-obj. Try this:

var output = createJSON1();

function createJSON1() {
  let obj = {
    name: $('#srch-obj').val(),
    objects: $("#select1 > option").map((t, el) => ({
      type: "Host",
      id: el.value
    })).get()
  }
  return JSON.stringify(obj);
}

console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="text" id="srch-obj" value="GROUP-X1">
<select id="select1" multiple size="2" style="width: 480px">
  <option>0050569A-7800-0ed3-0000-008589948757</option>
  <option>0050569A-7800-0ed3-0000-008589945523</option>
</select>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related