객체를 포함하는 배열을 반복하고 속성에 액세스하는 방법
배열에 포함 된 객체를 순환하고 각 객체의 속성을 변경하고 싶습니다. 내가 이렇게하면 :
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 () 메서드는 제공된 테스트 함수를 만족하는 배열의 첫 번째 요소 값을 반환합니다.
참고 문헌
- Array.prototype.some ()
- Array.prototype.forEach ()
- Array.prototype.map ()
- Array.prototype.filter ()
- Array.prototype.sort ()
- 확산 구문
- Array.prototype.find ()
ECMAScript 2015 aka ES6에서는 for..of 루프 를 사용하여 객체 배열을 반복 할 수 있습니다 .
for (let item of items) {
console.log(item); // Will display contents of the object inside the array
}
이 답변을 게시 할 때 Internet Explorer에 대한 지원은 존재하지 않지만 Traceur 또는 Babel과 같은 변환기를 사용하면 브라우저가 무엇을 지원하는지 실제로 걱정할 필요없이 이와 같은 새로운 Javascript 기능을 사용할 수 있습니다.
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
Here's an example on how you can do it :)
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])
}
}
Looping through an array of objects is a pretty fundamental functionality. This is what works for me.
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]
is logically incorrect.
Use (myArray[j].x);
instead
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
It's really simple using the forEach method since ES5+. You can directly change each property of each object in your array.
myArray.forEach(function (arrayElem){
arrayElem = newPropertyValue;
});
If you want to access a specific property on each object:
myArray.forEach(function (arrayElem){
arrayElem.nameOfYourProperty = newPropertyValue;
});
Here's another way of iterating through an array of objects (you need to include jQuery library in your document for these).
$.each(array, function(element) {
// do some operations with each element...
});
This would work. Looping thorough array(yourArray) . Then loop through direct properties of each object (eachObj) .
yourArray.forEach( function (eachObj){
for (var key in eachObj) {
if (eachObj.hasOwnProperty(key)){
console.log(key,eachObj[key]);
}
}
});
Array object iteration, using jQuery, (use the second parameter to print the string).
$.each(array, function(index, item) {
console.log(index, item);
});
Accepted answer uses normal function. So posting the same code with slight modification using arrow function on forEach
yourArray.forEach(arrayItem => {
var x = arrayItem.prop1 + 2;
console.log(x);
});
또한 $ .each에서 아래와 같이 화살표 기능을 사용할 수 있습니다
$.each(array, (item, index) => {
console.log(index, item);
});
var c = {
myProperty: [
{ name: 'this' },
{ name: 'can' },
{ name: 'get' },
{ name: 'crazy' }
]
};
c.myProperty.forEach(function(myProperty_element) {
var x = myProperty_element.name;
console.log('the name of the member is : ' + x);
})
이것이 내가 그것을 달성 할 수 있었던 방법 중 하나입니다.
const jobs = [
{
name: "sipher",
family: "sipherplus",
job: "Devops"
},
{
name: "john",
family: "Doe",
job: "Devops"
},
{
name: "jim",
family: "smith",
job: "Devops"
}
];
const txt =
` <ul>
${jobs.map(job => `<li>${job.name} ${job.family} -> ${job.job}</li>`).join('')}
</ul>`
;
document.body.innerHTML = txt;
등 진드기에주의하십시오 (`)
'programing tip' 카테고리의 다른 글
Visual Studio 2015 또는 2017에서 단위 테스트를 찾지 못함 (0) | 2020.06.05 |
---|---|
백분율 높이 HTML 5 / CSS (0) | 2020.06.05 |
Docker에 볼륨을 추가하지만 하위 폴더는 제외 (0) | 2020.06.05 |
생년월일 및 getDate ()를 기준으로 연령 (년)을 계산하는 방법 (0) | 2020.06.05 |
jQuery로 입력 값을 설정 한 후 각도 모델 업데이트 (0) | 2020.06.05 |