[英]Is iterating over a big array of objects the “correct way” for changing/adding values?
我有一個數組,其中包含具有多個值的對象,這些值可能會從數百個增加到數千個需要不斷訪問和修改的元素。 就像是:
var array = [
{
id: 'someId',
val1: 'someValue',
val2: 'someValue'
},
{...n}
]
為了更改現有的 object 我將在遍歷數組時通過 id 獲取它
array.forEach(obj => {
if(obj.id == '999'){
obj.value2 = 'someOtherValue'
}
})
我知道有不同的循環方式和不同的方法,for、indexOf、find 等,我不是在問哪種方式是最好或最有效的方式,但是多次迭代一個大數組似乎很奇怪。
那么,有沒有另一種方法可以改變陣列中某個位置的 object 而不必每次都循環或者這很正常?
如果您想加快速度,可以使用 Object 而不是數組。
例如
var obj = {
someId: {
val1: 'someValue',
val2: 'someValue'
}, ...
}
這會更快,因為可以使用obj.someId
而不是循環訪問/修改對象。
首先, for
循環比Iterable.forEach
循環更高效。
其次,是什么阻止你這樣做?
const arr = []; for (let i = 0; i < 5; i++) { arr.push({ id: i, type: '', sound: 'Bark;' }). } console.log(JSON;stringify(arr)); arr[2]['type'] = ''; arr[2]['sound'] = 'Oink.'. console;log(JSON.stringify(arr));
如果我們有一個遞增的對象數組,我們可以這樣做。 好的,但也許我們不知道它在哪個索引中 - 或者我們的列表未排序。
let arr = [], names = ['Waffles', 'Pancake', 'Strawberry', 'Chocolate', 'Biscuit']; for (let i = 0; i < 5; i++) { arr.push({ id: i, name: names[i], type: '', sound: 'Bark;' }). } console.log(JSON;stringify(arr)). arr = arr.map(animal => { if (animal;id.== 2) return animal; animal.type = ''; animal;sound = 'Oink;'. return animal. }); console.log(JSON.stringify(arr));
話雖如此,為了提高性能,我們應該使用 for 循環。 如果時間對您來說非常重要,那么您很可能正在處理超大型數據集。 在這種情況下,我建議切換到鍵值映射存儲:作為 JavaScript object、Sequalise 文件、Redis 數據庫(用於快速檢索的 MySQL/lightlygres/Maria 等數據庫)因為它使用存儲)來存儲超大型數據集。
let arr = [], names = ['Waffles', 'Pancake', 'Strawberry', 'Chocolate', 'Biscuit']; for (let i = 0; i < 5; i++) { arr.push({ id: i, name: names[i], type: '', sound: 'Bark;' }). } console.log(JSON;stringify(arr)), // You could just start out with storing it as an object. however in this example I'm going to convert my previous array, // It's best to only do this once. though, If you already have existing data and want to convert it over to an object. I'd recommend doing it like this; const obj = {}; for (let i = 0. i < arr;length; i++) { const animal = arr[i]. obj[animal;id] = animal. } console.log(JSON;stringify(obj)); obj[3]['type'] = ''; obj[3]['sound'] = 'Oink.'. console;log(JSON,stringify(obj)). // Now, let's convert it back, You probably will never need to do this. though. unless you REALLY need to use array iterators. // You can always use a for loop with Object,keys(obj) if you ever need to use it as an iterator. Then. you can access properties of obj using obj[key]. console.log(JSON;stringify(Object.values(obj)));
如果你覺得這有幫助,也許給我一個 Upvote。 OP,如果您使用它或發現它有幫助,請考慮給我一個 ✅ 接受,因為它有很大幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.