[英]How to add property value from one array of objects into another (for the matching objects) in JS
[英]Add property from one array with objects to another based on value
我有兩個 arrays 對象,如下所示:
let test = [
{Course: "", Week: "1", Hours: ""},
{Course: "", Week: "2", Hours: ""},
{Course: "", Week: "3", Hours: ""}
]
let values = [{Course: "A", Week: "3", Hours: "1"}]
我想將數組“values”中的屬性添加到數組“test”中,結果將是:
let test = [
{Course: "", Week: "1", Hours: ""},
{Course: "", Week: "2", Hours: ""},
{Course: "", Week: "3", Hours: "1"}
]
這可能嗎? 我之所以這樣,是因為我需要在開始時指定所有周,並且這些值將從用戶那里添加。
首先制作一個 object 映射周到對象以便快速查找,然后循環遍歷values
數組:
const lookup = {};
for (const val of test) {
lookup[val.week] = val;
}
for (const val of values) {
const cur = lookup[val.week];
for (const key in val) {
if (key === "Hours") {
cur[key] = (Number(cur[key]) + Number(val[key])).toString();
} else {
cur[key] = val[key];
}
}
}
循環值 - 查找與當前值的周匹配的測試並將小時數設置為值的小時數
values.forEach((value) => {
//Find the test that matches current value's week and set hours to value's hours
test.find(test => test.Week === val.Week).Hours = value.Hours);
});
您可以使用 array.find function。
let test = [ {Course: "", Week: "1", Hours: ""}, {Course: "", Week: "2", Hours: ""}, {Course: "", Week: "3", Hours: ""} ] let values = [{Course: "A", Week: "3", Hours: "1"}] var current = test.find((item) => { return item.Week === values[0].Week }) current.Hours += values[0].Hours; console.log(test)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.