gpt4 book ai didi

javascript - 如何在 ReactJS 中将对象插入数组

转载 作者:行者123 更新时间:2023-12-05 03:32:20 28 4
gpt4 key购买 nike

我有以下情况。我正在从后端获取数据,响应是一堆对象。我想迭代它们,在每次迭代中,我想将它们插入我的状态。

这是我从后端获取数据的方式:

     const allBookings = useSelector(getBookings);

useEffect(() => {
dispatch(
fetchBookings.request({
getAll: true,
})
);
}, [dispatch]);

这是我的数据:

bookings:{
0:{id: 294, address: '1585 Charleston Rd, Mountain View, CA, USA', broker:{name:'aaa'}},
1:{id: 294, address: '1586 Charleston Rd, Mountain View, CA, USA', broker:{name:'bbb'}},
2:{id: 294, address: '1587 Charleston Rd, Mountain View, CA, USA', broker:{name:'ccc'}}
}

在这里,我试图将我的数据设置在一个数组中,但出了点问题,请帮助我弄清楚如何实现。最终的结果应该是这样的:

    [
{id: 294, address: '1585 Charleston Rd, Mountain View, CA, USA', broker:{name:'aaa'}},
{id: 294, address: '1586 Charleston Rd, Mountain View, CA, USA', broker:{name:'bbb'}},
{id: 294, address: '1587 Charleston Rd, Mountain View, CA, USA', broker:{name:'ccc'}}
]
     if (!allBookings) return null;

const book = allBookings.bookings;
const [books, setBooks] = useState([]);
useEffect(() => {
if (book) {
const x = Object.entries(book);
setBooks(x);
}
}, [book]);

console.log('books===>', books);

here is my code in sandbox

最佳答案

改变 const x = Object.entries(book); const x = Object.values(book);

关于javascript - 如何在 ReactJS 中将对象插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70504702/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com