2017-10-11 61 views
0

我有一個表示對象(人)列表的JSON數組。每個對象(每個人)都有名稱屬性,圖像和數字數組。在另一個陣列內更新數組

實施例:

"people":[ 
    { 
     "name":"nunu", 
     "image":"image1", 
     "numbers":{ 
     "total":50, 
     "vector":[ 
      10, 
      20, 
      5, 
      10, 
      5 
     ] 
     } 
    } 
]; 

我的目標是更新所有的載體和附加一些計算到每個矢量。

這是我的嘗試:

this.people = this.people.map((person) => { 
     return person.numbers.vector.map((num) => { 
     return Math.round(((num/divider) * 100)/100); 
     }); 
    }); 

的問題是,people被替換爲數字在我vector,我失去了人的數據。

如何更新矢量而不會改變任何其他數據?

+0

使用'.forEach()'外部陣列上,並且只更新'人.nu​​mbers.vector'爲每一個。 – Pointy

+3

你濫用'.map' – TKoL

回答

1

由於.map() specification它創建了一個新的數組,處理最高級別列表使用.forEach()代替:

this.people.forEach(person => 
    person.numbers.vector = person.numbers.vector.map(num => 
    Math.round(((num/divider) * 100)/100) 
); 
); 
0

如果使用新的傳播經營者和像通天塔某事,這變得微不足道:

const source = { 
    "people": [{ 
    "name": "nunu", 
    "image": "image1", 
    "numbers": { 
     "total": 50, 
     "vector": [ 
     10, 
     20, 
     5, 
     10, 
     5 
     ] 
    } 
    }] 
}; 

const newSource = { 
    ...source, 
    people: source.people.map(person => { 
    return { 
     ...person, 
     numbers: { 
     ...person.numbers, 
     vector: person.numbers.vector.map(n => Math.round(((n/2) * 100)/100)) 
     } 
    } 
    }) 
}; 

這裏是更多關於spread運營商。

作爲一個附註,使用spread運算符創建一個新對象,並使用map創建一個新數組。這樣你將永遠有一個新的對象,不能改變舊的。使用const這種類型的代碼也是一種很好的做法。

0
people = people.map((person) => { 
    person.numbers.vector = person.numbers.vector.map((num) => { 
     return Math.round(((num/divider) * 100)/100); 
    }); 
    return person; 
}); 

您正在返回矢量作爲人的價值,您需要更改矢量的值,然後返回人。

0

嘗試使用spread運算符更新人員對象並保存所有數據。例如,計算total值NUMS的總和:

this.people = this.people.map((person) => { 
    let total = person.numbers.vector.reduce((prevNum, nextNum) => { 
    return prevNum + nextNum; 
    }); 

    return { 
     ...person, 
     numbers: { 
     ...person.numbers, 
     total 
     } 

    } 
}); 

在你可以改變矢量值的方法相同,例如

相關問題