简体   繁体   中英

adding to elements in array of objects using React Hooks

const roomData = [{
        name: 1,
        data: [{
                x: 102,
                y: 35
            },
            {
                x: 105,
                y: 40
            }
        ]
    },
    {
        name: 2,
        data: [{
            x: 104,
            y: 36
        }, {
            x: 105,
            y: 40
        }]
    }
}

This is my array.

(response.data).forEach((room) => {
            setRoomData(roomData => [...roomData, {
                name: room['floor'],
                data: [{
                    x: room['Roomnumber'],
                    y: room['room_temperature']
                }]
            }]);

This is how I set RoomData. I need to add another x and y pair in data property on fetching.How to do this using react hooks?

So to add data to room(s) with name of roomToChange you can use Array.prototype.map:

roomData.map((room) =>
  room.name === roomToChange
    ? { ...room, data: room.data.concat(extraItem) }
    : room
);

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