[英]Add property from one array with objects to another based on value
I have two arrays of objects like this:我有两个 arrays 对象,如下所示:
let test = [
{Course: "", Week: "1", Hours: ""},
{Course: "", Week: "2", Hours: ""},
{Course: "", Week: "3", Hours: ""}
]
let values = [{Course: "A", Week: "3", Hours: "1"}]
I want to add the property from array "values" to array "test so the result will be:我想将数组“values”中的属性添加到数组“test”中,结果将是:
let test = [
{Course: "", Week: "1", Hours: ""},
{Course: "", Week: "2", Hours: ""},
{Course: "", Week: "3", Hours: "1"}
]
Is this possible?这可能吗? The reason why I have it like this, is I need to specify all weeks at the start, and the values will be added from the user.
我之所以这样,是因为我需要在开始时指定所有周,并且这些值将从用户那里添加。
First make an object mapping weeks to objects for fast lookup then just loop through the values
array:首先制作一个 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];
}
}
}
Loop through Values - Find the test that matches current value's week and set hours to value's hours循环值 - 查找与当前值的周匹配的测试并将小时数设置为值的小时数
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);
});
You can just use array.find function.您可以使用 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.