[英]How to loop through an array containing objects and access their properties
我想循環遍歷數組中包含的對象並更改每個對象的屬性。 如果我這樣做:
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j]);
}
控制台應該會調出陣列中的每個 object,對吧? 但實際上它只顯示第一個 object。 如果我在循環之外對數組進行控制台記錄,所有對象都會出現,所以肯定會有更多。
無論如何,這是下一個問題。 如何使用循環訪問,例如數組中的 Object1.x?
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j.x]);
}
這將返回“未定義”。 循環外的控制台日志再次告訴我這些對象都有“x”的值。 如何在循環中訪問這些屬性?
有人建議我在其他地方為每個屬性使用單獨的 arrays,但我想確保我首先用盡了這條途徑。
謝謝!
使用 forEach 它是一個內置的數組函數。 Array.forEach()
:
yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});
在 JavaScript 中以函數式編程方式循環遍歷數組的一些用例:
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() 嚴格來說不是函數式的,因為它作為輸入參數的函數不應該返回值,因此不能被視為純函數。
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
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]
注意:map() 方法使用對調用數組中的每個元素調用提供的函數的結果創建一個新數組。
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
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]
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}
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}]
注意: filter() 方法創建一個新數組,其中包含通過所提供函數實現的測試的所有元素。
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);
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
循環最好的事情for..of
是它們可以迭代的不僅僅是數組。 您可以迭代任何類型的可迭代對象,包括地圖和對象。 如果您需要支持舊瀏覽器,請確保使用轉譯器或類似 TypeScript 的東西。
如果你想遍歷一個映射,語法與上面大致相同,除了它同時處理鍵和值。
for (const [key, value] of items) {
console.log(value);
}
我在 Javascript 中進行的幾乎所有類型的迭代都使用for..of
循環。 此外,最酷的事情之一是它們也可以與 async/await 一起使用。
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[jx]
在邏輯上是不正確的。
使用(myArray[j].x);
反而
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
從 ES5+ 開始,使用 forEach 方法真的很簡單。 您可以直接更改數組中每個對象的每個屬性。
myArray.forEach(function (arrayElem){
arrayElem = newPropertyValue;
});
如果要訪問每個對象的特定屬性:
myArray.forEach(function (arrayElem){
arrayElem.nameOfYourProperty = newPropertyValue;
});
這會奏效。 循環徹底 array(yourArray) 。 然后循環遍歷每個對象 (eachObj) 的直接屬性。
yourArray.forEach( function (eachObj){
for (var key in eachObj) {
if (eachObj.hasOwnProperty(key)){
console.log(key,eachObj[key]);
}
}
});
這是遍歷對象數組的另一種方法(您需要在文檔中包含 jQuery 庫以用於這些對象)。
$.each(array, function(element) {
// do some operations with each element...
});
數組對象迭代,使用jQuery,(使用第二個參數打印字符串)。
$.each(array, function(index, item) {
console.log(index, item);
});
接受的答案使用正常功能。 因此,在 forEach 上使用箭頭函數稍微修改后發布相同的代碼
yourArray.forEach(arrayItem => {
var x = arrayItem.prop1 + 2;
console.log(x);
});
同樣在 $.each 中,您可以使用如下箭頭函數
$.each(array, (item, index) => {
console.log(index, item);
});
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;
小心后面的勾號 (`)
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); })
這是我如何能夠實現它的方式之一。
這可能會幫助某人。 可能是 Node.js 的一個 bug。
var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;
這不起作用:
while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined
但這有效...
while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.
這也有效...
while ((arr[c]) && (arr[c].name)) { c++; }
但簡單地顛倒順序是行不通的。 我猜這里有某種內部優化破壞了 Node.js。
while ((arr[c].name) && (arr[c])) { c++; }
錯誤表示數組未定義,但不是:-/ Node v11.15.0
我知道這已經很長時間了,但是對於遇到此問題的其他任何人,我的問題是我正在循環遍歷僅包含一個數組的數組。 像這樣:
// array snippet (returned from here)
} else {
callback([results])
}
我正在使用這樣的數組
for(const result of results){
console.log(result.x)
}
如您所見,我想要迭代的數組實際上在另一個數組中。 刪除方括號有幫助。 節點 JS 和 MySQL。
for (element in array) {
console.log(array[element].property);
}
這有效。
this.data = [{name:"Rajiv", city:"Deoria"},{name:"Babbi", city:"Salempr"},{name:"Brijesh", city:"GKP"}];
for(const n of this.data) {
console.log(n.name)
}
我想同時循環和解構賦值,所以代碼如下: config.map(({ text, callback })=>add_btn({ text, callback }))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.