source

JavaScript는 JSON 어레이를 통해 루프합니까?

myloves 2023. 4. 3. 21:54

JavaScript는 JSON 어레이를 통해 루프합니까?

다음 json 어레이를 루프하려고 합니다.

{
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "hello1@email.se"
}, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "hello2@email.se"
}

그리고 다음을 시도했다.

for (var key in data) {
   if (data.hasOwnProperty(key)) {
      console.log(data[key].id);
   }
}

하지만 어떤 이유에서인지 첫 번째 부분인 ID 1 값만 얻습니다.

좋은 생각 있어요?

JSON은 다음과 같습니다.

let json = [{
    "id" : "1", 
    "msg"   : "hi",
    "tid" : "2013-05-05 23:35",
    "fromWho": "hello1@email.se"
},
{
    "id" : "2", 
    "msg"   : "there",
    "tid" : "2013-05-05 23:45",
    "fromWho": "hello2@email.se"
}];

어레이를 다음과 같이 루프 오버할 수 있습니다.

for(let i = 0; i < json.length; i++) {
    let obj = json[i];

    console.log(obj.id);
}

또는 이와 같이(Eric의 제안) IE 지원에 주의해 주십시오.

json.forEach(function(obj) { console.log(obj.id); });

코드에는 몇 가지 문제가 있습니다.먼저 json은 다음과 같이 되어 있어야 합니다.

var json = [{
"id" : "1", 
"msg"   : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "hello1@email.se"
},
{
"id" : "2", 
"msg"   : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}];

다음에, 다음과 같이 반복할 수 있습니다.

for (var key in json) {
if (json.hasOwnProperty(key)) {
  alert(json[key].id);
  alert(json[key].msg);
}
}

그리고 그것은 완벽한 결과를 낳는다.

여기를 클릭해 주세요.http://jsfiddle.net/zrSmp/

이거 먹어봐

var json = [{
    "id" : "1", 
    "msg"   : "hi",
    "tid" : "2013-05-05 23:35",
    "fromWho": "hello1@email.se"
},
{
    "id" : "2", 
    "msg"   : "there",
    "tid" : "2013-05-05 23:45",
    "fromWho": "hello2@email.se"
}];

json.forEach((item) => {
  console.log('ID: ' + item.id);
  console.log('MSG: ' + item.msg);
  console.log('TID: ' + item.tid);
  console.log('FROMWHO: ' + item.fromWho);
});
var arr = [
  {
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "hello1@email.se"
  }, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "hello2@email.se"
  }
];

각 방법에 따라 쉽게 구현할 수 있습니다.

arr.forEach(function(item){
  console.log('ID: ' + item.id);
  console.log('MSG: ' + item.msg);
  console.log('TID: ' + item.tid);
  console.log('FROMWHO: ' + item.fromWho);
});

이미 조사를 시작했으니

var data = [{
    "id": "1",
    "msg": "hi",
    "tid": "2013-05-05 23:35",
    "fromWho": "hello1@email.se"
}, {
    "id": "2",
    "msg": "there",
    "tid": "2013-05-05 23:45",
    "fromWho": "hello2@email.se"
}]

그리고 이 기능은

var iterateData =function(data){   for (var key in data) {
       if (data.hasOwnProperty(key)) {
          console.log(data[key].id);
       }
    }};

이렇게 부르면 돼

iterateData(data); // write 1 and 2 to the console

Erics 코멘트 후 업데이트

에릭지적했듯이 어레이의 루프는 예기치 않은 결과를 초래할 수 있습니다.참조된 질문은 장단점에 대해 장황하게 논의한다.

테스트 대상(var i...)

하지만 그 다음 단계는 꽤 세이브된 것 같습니다.

for(var i = 0; i < array.length; i += 1)

크롬 테스트 결과는 다음과 같습니다.

var ar = [];
ar[0] = "a"; 
ar[1] = "b";
ar[4] = "c";

function forInArray(ar){ 
     for(var i = 0; i < ar.length; i += 1) 
        console.log(ar[i]);
}

// calling the function
// returns a,b, undefined, undefined, c, undefined
forInArray(ar); 

테스트 대상.forEach()

적어도 크롬 30에서는 예상대로 작동합니다.

var logAr = function(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
ar.forEach(logAr); // returns a[0] = a, a[1] = b, a[4] = c

링크

되고 있어요.방금 JSON 데이터에 대괄호를 추가했습니다.데이터는 다음과 같습니다.

var data = [
    { 
        "id": "1",
        "msg": "hi", 
        "tid": "2013-05-05 23:35", 
        "fromWho": "hello1@email.se" 
    }, 
    { 
        "id": "2", 
        "msg": "there", 
        "tid": "2013-05-05 23:45", 
        "fromWho": "hello2@email.se"
    }
]

루프는 다음과 같습니다.

for (var key in data) {
   if (data.hasOwnProperty(key)) {
         alert(data[key].id);
   }
} 

데이터 스니펫을 약간 확장해야 합니다.이렇게 해야 JSON이 제대로 됩니다.어레이 이름 속성만 포함하면 됩니다.item.

{
  "item": [{
    "id": "1",
    "msg": "hi",
    "tid": "2013-05-05 23:35",
    "fromWho": "hello1@email.se"
  }, {
    "id": "2",
    "msg": "there",
    "tid": "2013-05-05 23:45",
    "fromWho": "hello2@email.se"
  }]
}

JavaScript는 단순합니다.

var objCount = json.item.length;
for (var x = 0; x < objCount; x++) {
  var curitem = json.item[x];
}

반복하려면 배열이어야 합니다.실종되신 것 같습니다[그리고.].

var x = [{
    "id": "1",
        "msg": "hi",
        "tid": "2013-05-05 23:35",
        "fromWho": "hello1@email.se"
}, {
    "id": "2",
        "msg": "there",
        "tid": "2013-05-05 23:45",
        "fromWho": "hello2@email.se"
}];

var $output = $('#output');
for(var i = 0; i < x.length; i++) {
    console.log(x[i].id);
}

다음 jsfiddle을 참조하십시오.http://jsfiddle.net/lpiepiora/kN7yZ/

조금 늦었지만 다른 사람들을 도울 수 있기를 바랍니다:D

니 아들은 니클라스가 이미 말한 것처럼 보여야 해그리고 여기 있습니다.

for(var key in currentObject){
        if(currentObject.hasOwnProperty(key)) {
          console.info(key + ': ' + currentObject[key]);
        }
   }

다차원 배열이 있는 경우 코드는 다음과 같습니다.

for (var i = 0; i < multiDimensionalArray.length; i++) {
    var currentObject = multiDimensionalArray[i]
    for(var key in currentObject){
            if(currentObject.hasOwnProperty(key)) {
              console.info(key + ': ' + currentObject[key]);
            }
       }
}

콤마로 구분된 두 개의 JSON 개체가 있습니다.둘 다 어레이 내에 있는 경우([...])가 더 말이 됩니다.

또한 어레이 내부에 있는 경우에는 표준 "var i = 0..."을 사용합니다.루프의 타입.현 상태에서는 문자열 "1"의 "id" 속성을 취득하고 "hi"의 "id" 등을 취득하려고 합니다.

아주 쉬운 방법!

var tire_price_data = JSON.parse('[{"qty":"250.0000","price":"0.390000"},{"qty":"500.0000","price":"0.340000"},{"qty":"1000.0000","price":"0.290000"}]'); 
tire_price_data.forEach(function(obj){
    console.log(obj);
    console.log(obj.qty);
    console.log(obj.price);
})

감사해요.

var json = {
    "persons": [
        {"name": "Lili", "age": 23, "is_student": true},
        {"name": "James", "age": 24, "is_student": true},
        {"name": "John", "age": 25, "is_student": false}
    ]
};

for (var key in json.persons) {
    for (var keyName in json.persons[key]) {
        alert(keyName + ': ' + (json.persons[key])[keyName]);
    }
}

//출력: 이름:Lili, 23세, is_student: 참, ...

화살표 기능을 사용하는 짧은 솔루션

var data = [{
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "hello1@email.se"
}, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "hello2@email.se"
}];
data.map((item, i) => console.log('Index:', i, 'Id:', item.id));

그리고 그 부동산이 그 부동산이"id"는 현재 사용되지 않습니다.

var data = [{
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "hello1@email.se"
}, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "hello2@email.se"
}, {
  "msg": "abcde",
  "tid": "2013-06-06 23:46",
  "fromWho": "hello3@email.se"
}];

data.filter(item=>item.hasOwnProperty('id'))
                .map((item, i) => console.log('Index:', i, 'Id:', item.id));

for-loop을 사용하여 값을 얻을 수 있습니다.구조를 해제할 수 있습니다.

const arr = [
        {
            id:123,
            desc:"do something",
            isDone:false
        },
        {
            id:124,
            desc:"do something",
            isDone:true
        }
    ]

for(let _i in arr){
    let {id, desc, isDone} = arr[_i]
    // do something
    console.log({id, desc, isDone});
}


언급URL : https://stackoverflow.com/questions/18238173/javascript-loop-through-json-array