gpt4 book ai didi

javascript - JS 使用新键创建一个新的对象数组

转载 作者:行者123 更新时间:2023-11-29 15:12:52 27 4
gpt4 key购买 nike

所以我有两个 JSON 对象数组、房间和预订。我想输出一个新的对象数组,这些对象的数据从这两个数组中组合而成,具有新的数据类型。不确定如何创建新数据类型。

var rooms = [
{id:1, room:'treehouse'},
{id:2, room:'casa'},
{id:3, room:'vacation'},
{id:4, room:'presidential'}
];

var reservations = [
{id:1, roomID:'2', time:'2pm', location:'rome'},
{id:2, roomID:'3', time:'4pm', location:'paris'},
{id:3, roomID:'1', time:'4pm', location:'london'},
{id:4, roomID:'2', time:'7pm', location:'rome'},
{id:5, roomID:'1', time:'12pm', location:'london'},
{id:6, roomID:'4', time:'4pm', location:'berlin'}
];

期望的输出:

var bookings = [
{id: 1, roomid:1, time:'12pm',location:'london', roomname:'treehouse'},
{id: 2, roomid:1, time:'4pm', location:'london', roomname:'treehouse'},
{id: 3, roomid:2, time:'2pm', location:'rome', roomname:'casa'},
{id: 4, roomid:2, time:'7pm', location:'rome', roomname:'casa'},
{id: 5, roomid:3, time:'4pm', location:'paris', roomname:'vacation'},
{id: 6, roomid:4, time:'4pm', location:'berlin', roomname:'presidential'}
]

我对如何执行此操作的逻辑感到困惑。我正在考虑迭代 reservations 数组,并为每个预订获取 roomId 并检查房间的 map 结构,然后输出。我不太确定该怎么做。

最佳答案

var rooms = [
{id:1, room:'treehouse'},
{id:2, room:'casa'},
{id:3, room:'vacation'},
{id:4, room:'presidential'}
];

var reservations = [
{id:1, roomID:'2', time:'2pm', location:'rome'},
{id:2, roomID:'3', time:'4pm', location:'paris'},
{id:3, roomID:'1', time:'4pm', location:'london'},
{id:4, roomID:'2', time:'7pm', location:'rome'},
{id:5, roomID:'1', time:'12pm', location:'london'},
{id:6, roomID:'4', time:'4pm', location:'berlin'}
];

console.log(
reservations.map(a=>({...a, roomname: rooms.find(b=>b.id==a.roomID).room}))
)

关于javascript - JS 使用新键创建一个新的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52503446/

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