如何在对象中传播嵌套属性? [英] How to spread nested properties in Object?

查看:42
本文介绍了如何在对象中传播嵌套属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有这个对象.我想知道如何选择特定项目并更新属性.例如.项目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
     }
  }
};

这篇关于如何在对象中传播嵌套属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆