如何在对象中传播嵌套属性?

编程入门 行业动态 更新时间:2024-10-10 04:27:55
本文介绍了如何在对象中传播嵌套属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在下面有这个对象.我想知道如何选择特定项目并更新属性.例如.项目1我想在数组中添加一个任务.

I have this object below. I was wondering how I can select a specific item and update a property. For example. Item 1 I want to add a task in the array.

item: { 'item-1': { id: 'item-1', title: 'To do', task: ['task-1', 'task-2', 'task-3', 'task-4'] }, 'item-2': { id: 'item-2', title: 'In progress', task: [] },

我目前有

const getItem = {...state.items['item-1']} const newTaskList = [...getItem.task, newTask.id] const newState = { ...state, items: { ...state.items, //How do I spread new array correctly in item 1? //...state.items['item-1'].task } };

推荐答案

您需要使用对象键(即 item-1 )并为其克隆属性,并为任务键添加新列表.简而言之,您需要先克隆对象的每个级别,然后再覆盖要更新的密钥

You need to use the object key i.e item-1 and clone the properties for it and add the new list for the task key. In short you need to clone at each level of the object before overriding the key that you wish to update

const newState = { ...state, items: { ...state.items, 'item-1': { ...state.items['item-1'], task: newTaskList } } };

更多推荐

如何在对象中传播嵌套属性?

本文发布于:2023-11-05 10:03:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560545.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   在对   象中   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!