[javascript] 객체를 포함하는 배열을 반복하고 속성에 액세스하는 방법

배열에 포함 된 객체를 순환하고 각 객체의 속성을 변경하고 싶습니다. 내가 이렇게하면 :

for (var j = 0; j < myArray.length; j++){

console.log(myArray[j]);

}

콘솔은 배열의 모든 객체를 가져와야합니다. 그러나 실제로 첫 번째 개체 만 표시합니다. 루프 외부에서 배열을 콘솔 로그하면 모든 객체가 나타나므로 분명히 더 많이 있습니다.

어쨌든 다음 문제가 있습니다. 루프를 사용하여 배열의 Object1.x와 같이 어떻게 액세스합니까?

for (var j = 0; j < myArray.length; j++){

console.log(myArray[j.x]);

}

“정의되지 않음”을 반환합니다. 루프 외부의 콘솔 로그는 객체에 모두 “x”값이 있음을 알려줍니다. 루프에서 이러한 속성에 어떻게 액세스합니까?

다른 곳에서 각 속성에 대해 별도의 배열을 사용하는 것이 좋지만 먼저이 길을 다 써야합니다.

감사합니다!



답변

내장 배열 함수에 forEach를 사용하십시오. Array.forEach():

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(x);
});


답변

JavaScript에서 함수형 프로그래밍 방식으로 배열을 반복하는 일부 사용 사례 :

1. 그냥 배열을 반복

const myArray = [{x:100}, {x:200}, {x:300}];

myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times
});

참고 : Array.prototype.forEach ()는 입력 매개 변수로받는 함수가 값을 리턴하지 않으므로 순수한 함수로 간주 될 수 없으므로 엄밀히 말하면 기능적인 방식은 아닙니다.

2. 배열의 요소 중 하나라도 테스트를 통과했는지 확인

const people = [
    {name: 'John', age: 23},
    {name: 'Andrew', age: 3},
    {name: 'Peter', age: 8},
    {name: 'Hanna', age: 14},
    {name: 'Adam', age: 37}];

const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true

3. 새로운 배열로 변환

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

참고 : map () 메서드는 호출 배열의 모든 요소에서 제공된 함수를 호출 한 결과로 새 배열을 만듭니다.

4. 특정 재산을 요약하고 평균을 계산

const myArray = [{x:100}, {x:200}, {x:300}];

const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300

const average = sum / myArray.length;
console.log(average); // 200

5. 원본을 기반으로하지만 수정하지 않고 새 어레이를 만듭니다.

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => {
    return {
        ...element,
        x: element.x * 2
    };
});

console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]

6. 각 카테고리의 수를 센다

const people = [
    {name: 'John', group: 'A'},
    {name: 'Andrew', group: 'C'},
    {name: 'Peter', group: 'A'},
    {name: 'James', group: 'B'},
    {name: 'Hanna', group: 'A'},
    {name: 'Adam', group: 'B'}];

const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
        return {...groups, A: A + 1};
    } else if (person.group === 'B') {
        return {...groups, B: B + 1};
    } else {
        return {...groups, C: C + 1};
    }
}, {});

console.log(groupInfo); // {A: 3, C: 1, B: 2}

7. 특정 기준에 따라 어레이의 서브 세트 검색

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}] 

참고 : filter () 메서드는 제공된 함수로 구현 된 테스트를 통과하는 모든 요소를 ​​사용하여 새 배열을 만듭니다.

8. 배열 정렬

const people = [
  { name: "John", age: 21 },
  { name: "Peter", age: 31 },
  { name: "Andrew", age: 29 },
  { name: "Thomas", age: 25 }
];

let sortByAge = people.sort(function (p1, p2) {
  return p1.age - p2.age;
});

console.log(sortByAge);

여기에 이미지 설명을 입력하십시오

9. 배열에서 요소 찾기

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');
console.log(john);

여기에 이미지 설명을 입력하십시오

Array.prototype.find () 메서드는 제공된 테스트 함수를 만족하는 배열의 첫 번째 요소 값을 반환합니다.

참고 문헌


답변

for..of 루프 를 사용하여 객체 배열을 반복 할 수 있습니다 .

for (let item of items) {
    console.log(item); // Will display contents of the object inside the array
}

for..of루프 의 가장 좋은 점 중 하나는 단순한 배열 이상의 것을 반복 할 수 있다는 것입니다. 맵과 객체를 포함하여 모든 반복 가능한 유형을 반복 할 수 있습니다. 구형 브라우저를 지원해야하는 경우 트랜스 파일러 또는 TypeScript와 같은 것을 사용해야합니다.

맵을 반복하려면 구문이 키와 값을 모두 처리한다는 점을 제외하면 위와 거의 동일합니다.

for (const [key, value] of items) {
  console.log(value);
}

for..ofJavascript에서 수행하는 거의 모든 종류의 반복에 루프를 사용 합니다. 또한 가장 멋진 것 중 하나는 비동기 / 대기 상태에서도 작동한다는 것입니다.


답변

for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}


답변

방법은 다음과 같습니다. 🙂

var students = [{
    name: "Mike",
    track: "track-a",
    achievements: 23,
    points: 400,
  },
  {
    name: "james",
    track: "track-a",
    achievements: 2,
    points: 21,
  },
]

students.forEach(myFunction);

function myFunction(item, index) {
  for (var key in item) {
    console.log(item[key])
  }
}


답변

객체 배열을 반복하는 것은 매우 기본적인 기능입니다. 이것이 저에게 효과적입니다.

var person = [];
person[0] = {
  firstName: "John",
  lastName: "Doe",
  age: 60
};

var i, item;

for (i = 0; i < person.length; i++) {
  for (item in person[i]) {
    document.write(item + ": " + person[i][item] + "<br>");
  }
}


답변

myArray[j.x] 논리적으로 잘못되었습니다.

사용 (myArray[j].x);하는 대신

for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}