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
uniqueIDofSelectandoptionValuein 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
'Programming' 카테고리의 다른 글
| POST 요청 json 데이터 보내기 java HttpUrlConnection (0) | 2020.08.24 | 
|---|---|
| iPhone 6 / iOS 8로 NFC 태그 읽기 (0) | 2020.08.24 | 
| 키 누르기 이벤트 후 jquery .val ()을 어떻게 얻을 수 있습니까? (0) | 2020.08.24 | 
| 디렉토리와 하위 디렉토리에서 가장 큰 파일을 찾는 방법은 무엇입니까? (0) | 2020.08.24 | 
| 새 Gradle 프로젝트 가져 오기 실패 : 빌드 도구 수정 버전 * .0.0을 찾지 못했습니다. (0) | 2020.08.24 |