0

I have two arrays of objects like this:

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:

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.

2
  • Why course in not changed in output Commented Nov 30, 2020 at 18:51
  • Only a single property is changed so you can use test[2].Hours = values[0].Hours Commented Nov 30, 2020 at 18:52

3 Answers 3

1

First make an object mapping weeks to objects for fast lookup then just loop through the values array:

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];
        }
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you! But if I have two values with the same week? E.g. let values = [{Course: "A", Week: "3", Hours: "1"}, {Course: "A", Week: "5", Hours: "1"}, {Course: "A", Week: "5", Hours: "1"}] Then it does not add them I guess
If you have multiple values with the same week then what's your goal? Is it to overwrite both?
@egx What's the expected behavior when two values have the same week?
My goal would then to add the hours in the same value. So I would have {Course: "A", Week: "5", Hours: "2"} if I have to values of Week 5 with 1 Hour in them
That would stay the same. So it only count the hours based on the weeks. The course actually is not that important, but rather the value of hours in weeks.
|
0

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);
});

Comments

0

You can just use 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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.