简体   繁体   中英

how to add new value to json

pin = [
    {
        "id": 26,
        "comments": [
            {
                "id": 2,
                "username": "user",
                "description": "example",
                "pin": 26,
                "commenter": 1
            },
            {
                "id": 3,
                "username": "admin",
                "description": "example",
                "pin": 26,
                "commenter": 17
            }
        ],  
    }
]

user would post a new comment and I would want it to add the new comment under the comments array I tried putting it this way but the other values turned out blank

   case ADD_COMMENT:
      return {
        ...state,
        pin: [...state.pin.commentstory, action.payload]
      };

how would you add a new value to the comments array?

This will add the action.payload to your pin array:

case ADD_COMMENT:
  return {
     ...state,
     pin: [...state.pin, action.payload]
  }

To add an item to the comments array in the pin array, you need a way to identify which item in the pin array should receive the update.

case ADD_COMMENT:
  // suggested payload structure
  const pinId = action.payload.pinId;
  const newComment = action.payload.comment;

  const newPins = state.pin.map(p => { 
     if (p.id !== pinId) { return p };
     return {...p, comments: [...p.comments, newComment]};
  });
  return {
    ...state,
    pin: newPins
  };

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