[英]Mapping Array Of Objects By Key
我有两个 arrays 是通过 reduce 方法创建的,该方法在两个现有的 arrays 中搜索日期。 然后它将这些日期转换为唯一的 object 密钥。
第一组是名称列表,第二组是一系列指令。
The goal is to combine the two arrays that get formed by finding like object keys and adding the matching list object and insert it into the set of instructions with the object key list.
一方面,它制作了一个如下所示的数组:
const listObj = [
{11/20/2020: [{name:'Joe', date:11/20/2020}]},
{11/26/2020 : [{name:'John', date:11/26/2020}]}
]
和这个:
const scheduleObj = [
{11/20/2020: {type:'Federal', date:11/20/2020}},
{11/26/2020 : {type:'State', date:11/26/2020}}
]
我需要的最终产品看起来像:
const scheduleObj = [
{11/26/2020 : {
type: 'State',
list: [{name:'John', date:11/26/2020}]
},
...
]
其中列表是添加的键,数组是与 object 键关联的数组
我使用了一种看起来像lodash
的凌乱方法来让它工作,但我认为必须有某种我可以做的映射。
任何帮助,将不胜感激
根据您在listObj
或scheduleObj
中的内容,这可能有点混乱,并且不是故障证明。 例如, scheduleObj
中的重复日期可能会导致使用此方法出现问题,如果日期在两个列表中都不是唯一的,您可能必须使用另一个key
。
scheduleObj.map((s) => {
// get the first key of the object as the date you're going to group with
const date = Object.keys(s)[0];
// filter the object that matches the date
const listObjFilter = listObj.filter((o) => Object.keys(o)[0] === date);
// get the list for the given date (or empty array if nothing found)
const listForDate = listObjFilter.length ? listObjFilter[0][date] : [];
// build the result object
return {
[date]: {
type: s[date]['type'],
list: listForDate
}
};
})
请注意,我一直认为您在listObj
或scheduleObj
的列表中的对象中只有一个键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.