简体   繁体   English

按键值对 JSON 数组进行分组

[英]Group JSON array by key value

Please help to combine object keys values from json arrays by key.请帮助按键组合来自 json 数组的对象键值。

 const input=[{ "Date":"04/10/2019", "Time":"15:35", "Title":"Flight -\ Group C", "Description":"Arrival 19:40" }, { "Date":"04/10/2019", "Time":"Evening", "Title":"Welcome drinks", "Description":"In the bar at\ " }, { "Date":"05/10/2019", "Time":"Morning", "Title":"Breakfast", "Description":"At leisure" }, { "Date":"05/10/2019", "Time":"10:00", "Title":"Something Else", "Description":"At leisure" }]; console.log( Object.values(input.reduce((a, { Date }) => { if (!a[Date]) a[Date] = { Date, activities: [] }; a[Date].activities.push(); return a; }, {})) );

I need a combined object keys values in javascript in the following way:我需要通过以下方式在 javascript 中组合对象键值:

 [ { "date":"04/10/2019", "activities":[ { "Time":"15:35", "Title":"Flight -\ Group C", "Description":"Arrival 19:40" }, { "Time":"Evening", "Title":"Welcome drinks", "Description":"In the bar at\ " } ] }, { "date":"05/10/2019", "activities":[ { "Time":"Morning", "Title":"Breakfast", "Description":"At leisure" } ] } ]

I am trying to get the result with my code but 'activities' are null... I would highly appreciate your help.我正在尝试使用我的代码获得结果,但“活动”为空...我非常感谢您的帮助。

Thank you in advance先感谢您

If you are using parameter destructuring you could use ... rest param to get other properties after you take out the date.如果您正在使用参数解构,您可以在取出日期后使用... rest param 来获取其他属性。

 const input=[{"Date":"04/10/2019","Time":"15:35","Title":"Flight - Group C","Description":"Arrival 19:40"},{"Date":"04/10/2019","Time":"Evening","Title":"Welcome drinks","Description":"In the bar at "},{"Date":"05/10/2019","Time":"Morning","Title":"Breakfast","Description":"At leisure"},{"Date":"05/10/2019","Time":"10:00","Title":"Something Else","Description":"At leisure"}] const object = input.reduce((r, { Date: date, ...rest}) => { if(!r[date]) r[date] = {date, activities: [rest]} else r[date].activities.push(rest) return r }, {}) const result = Object.values(object) console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM