user1893649
user1893649

Reputation: 177

Javascript - updating an object property with another value from the same object

I have the following object:

{ id: 1, name: 'jdoe', currentDayHours: null, totalHours: [{ task: 'cleaning', hours: 10}, { task: 'reading', hours: 2 }]}

I am trying to create a function that will update the currentDayHours based on the task parameter passed to the function. So for example, if "cleaning" is passed to the function, the expected outcome of the object should be:

{ id: 1, name: 'jdoe', currentDayHours: 10, totalHours: [{ task: 'cleaning', hours: 10}, { task: 'reading', hours: 2 }]}

I'm still new to javascript but I think I should use foreach and filter, but not sure how to use both with each other. Any guidance would be appreciated!

Upvotes: 0

Views: 35

Answers (2)

Duc Nguyen
Duc Nguyen

Reputation: 855

You can use Array.find() to find the task object in the totalHours array, and then use that object's hours to assign to currentDayHours.

If you want to modify the object in-place, you can do this:

function updateCurrentDayHours(obj, taskName) {
    const task = obj.totalHours.find(t => t.task === taskName)
    if (task) obj.currentDayHours = task.hours
}

If you want to return a cloned object, you can use a deepClone function provided by some libaries like lodash. Here I'm using JSON.parse() and JSON.stringify() for simplicity.

function updateCurrentDayHours(obj, taskName) {
    const task = obj.totalHours.find(t => t.task === taskName)
    if (task) {
        const clone = JSON.parse(JSON.stringify(obj))
        clone.currentDayHours = task.hours
        return clone
    }
}

Upvotes: 0

user120242
user120242

Reputation: 15268

Direct property access is enough. Use Array.find to find the object.

data = { id: 1, name: 'jdoe', currentDayHours: null, totalHours: [{ task: 'cleaning', hours: 10}, { task: 'reading', hours: 2 }]}

const updateHours = (data,key) => {
  data.currentDayHours = (data.totalHours.find(({task})=>task===key)||[]).hours
  return data
}

console.log(updateHours(data,'cleaning'))

Upvotes: 1

Related Questions