Programming

JavaScript for 루프로 json을 만드는 방법은 무엇입니까?

procodes 2020. 8. 24. 21:23
반응형

JavaScript for 루프로 json을 만드는 방법은 무엇입니까?


내가 가진 배열 을 선택 태그를.

<select id='uniqueID' name="status">
      <option value="1">Present</option>
      <option value="2">Absent</option>
 </select>

JavaScript에서 'uniqueIDofSelect 및 optionValue'필드가 두 개인 json 개체를 만들고 싶습니다.

getElementsByName ( "status")을 사용하고이를 반복합니다.

편집하다

나는 밖으로 넣어 필요

[{"selectID":2,"OptionValue":"2"},
{"selectID":4,"optionvalue":"1"}]

등등...


귀하의 요청에 대해 이해 한 바에 따르면 다음과 같이 작동합니다.

<script>
//  var status  = document.getElementsByID("uniqueID"); // this works too
var status  = document.getElementsByName("status")[0];
var jsonArr = [];

for (var i = 0; i < status.options.length; i++) {
    jsonArr.push({
        id: status.options[i].text,
        optionValue: status.options[i].value
    });
}
</script>

var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}

다음과 같은 단일 JavaScript 객체를 원하는 경우 :

{ uniqueIDofSelect: "uniqueID", optionValue: "2" }

(여기서 옵션 2, "Absent"는 현재 선택입니다) 다음 코드가이를 생성해야합니다.

  var jsObj = null;
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsObj = { uniqueIDofSelect: status.id, optionValue: options[i].value };
        break;
     }
  }

당신은 이러한 모든 객체의 배열 (선택된 하나뿐만 아니라) 사용하려는 경우 마이클의 코드 밖으로하지만 스왑 status.options[i].text를 들어 status.id.

선택한 객체의 JSON 표현이 포함 문자열원하면 다음을 대신 사용하십시오.

  var jsonStr = "";
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsonStr = '{ '
                  + '"uniqueIDofSelect" : '
                  + '"' + status.id + '"'
                  + ", "
                  + '"optionValue" : '
                  + '"'+ options[i].value + '"'
                  + ' }';
        break;
     }
  }

If I want to create JavaScript Object from string generated by for loop then I would JSON to Object approach. I would generate JSON string by iterating for loop and then use any popular JavaScript Framework to evaluate JSON to Object.

I have used Prototype JavaScript Framework. I have two array with keys and values. I iterate through for loop and generate valid JSON string. I use evalJSON() function to convert JSON string to JavaScript object.

Here is example code. Tryout on your FireBug Console

var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];

var json = "{ ";
for(var i = 0; i < key.length; i++) {
    (i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);

Your question is pretty hard to decode, but I'll try taking a stab at it.

You say:

I want to create a json object having two fields uniqueIDofSelect and optionValue in javascript.

And then you say:

I need output like

[{"selectID":2,"optionValue":"2"},
{"selectID":4,"optionvalue":"1"}]

Well, this example output doesn't have the field named uniqueIDofSelect, it only has optionValue.

Anyway, you are asking for array of objects...

Then in the comment to michaels answer you say:

It creates json object array. but I need only one json object.

So you don't want an array of objects?

What do you want then?

Please make up your mind.

참고URL : https://stackoverflow.com/questions/920930/how-to-create-json-by-javascript-for-loop

반응형