简体   繁体   中英

How to in javascript update inner object array with spread operator

I have in my reducer for a store, need to update an inner array object value:

for:

export interface SiteState {
  site: Site;
}

and

export interface Site {
  id: number | null;
  uuid: string;
  subscriptions?: (SubscriptionI)[] | null;
}

and would like update the site->subscriptions[x] = action.payload

// edited with solution

function handle(state: SiteState, action: Successaction): SiteState {
  const sub = state.site.subscriptions.map( subs => {
    if (subs.uuid === action.payload.uuid) {
      return action.payload
    } else {
      return subs;
    }
  });
  const site = { site: {...state.site, subscriptions: sub} };
  return site
}

I tried the spread operator but he just push my new subscriptions into the root site, si don"t know how write it for update the object SubscriptionI who is an array.

if you want to completely replace the subscriptions array then what you are doing is correct. However if you just want to add the whatever you have in action.payload to the subscriptions array than you need:

  const site = {...state.site, subscription**S**: [...state.site.subscription**S**, action.payload]};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM