1

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>

1 Answer 1

1

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>

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

2 Comments

No problem, glad to help
The get() call was in your original code, I simply copied it over. It retrieves the content from within the jQuery object. Normally this is a DOM Element, but as we've used map() it's an array. More info in the docs: api.jquery.com/get

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.