[英]Javascript - updating an object property with another value from the same object
I have the following object:我有以下 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.我正在尝试创建一个 function,它将根据传递给 function 的任务参数更新currentDayHours
。 So for example, if "cleaning" is passed to the function, the expected outcome of the object should be:因此,例如,如果将“清洁”传递给 function,则 object 的预期结果应该是:
{ 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.我对 javascript 还是新手,但我认为我应该使用foreach
和filter
,但不知道如何相互使用。 Any guidance would be appreciated!任何指导将不胜感激!
Direct property access is enough.直接访问财产就足够了。 Use Array.find to find the object.使用Array.find查找 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'))
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
.您可以使用Array.find()
在totalHours
数组中查找任务 object,然后使用该对象的hours
分配给currentDayHours
。
If you want to modify the object in-place , you can do this:如果要就地修改 object ,可以这样做:
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.如果您想返回一个克隆的 object,您可以使用一些库(如 lodash)提供的 deepClone function。 Here I'm using JSON.parse()
and JSON.stringify()
for simplicity.在这里,为了简单起见,我使用JSON.parse()
和JSON.stringify()
。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.