Javascript - 向数组中的对象添加新键

时间:2018-01-25 10:17:23

标签: javascript

任何人都可以告诉我如何实现以下

activity = {}   // can have hotel , transport etc
day = [ {day: 'DAY01'} , {day: 'DAY2'}]

我想将activity.hotel添加到day array中的day 01对象?

1 个答案:

答案 0 :(得分:0)

首先获得您想要的确切日期,例如使用find

然后使用括号表示法向日期对象添加新密钥,并分配您的活动对象。



let activity = { hotel: 'TheHotel' }   // can have hotel , transport etc
let days = [ {day: 'DAY01'} , {day: 'DAY2'}]

// get the particular day to edit
let day = days.find(d => d.day === 'DAY01')
// attach the activity.hotel object you want. 
day['hotel'] = activity.hotel;

console.log(days)




或直接添加整个活动对象,如果需要:



let activity = { hotel: 'TheHotel' }   // can have hotel , transport etc
let days = [ {day: 'DAY01'} , {day: 'DAY2'}]

// get the particular day to edit
let day = days.find(d => d.day === 'DAY01')
// attach the activity object you want. 
day['activity'] = activity;

console.log(days)