[英]Mapping Array Of Objects By Key
I have two arrays created from a reduce method that searches two existing arrays for dates.我有两个 arrays 是通过 reduce 方法创建的,该方法在两个现有的 arrays 中搜索日期。 It then turns those dates into unique object keys.
然后它将这些日期转换为唯一的 object 密钥。
The first group is a list of names the second is a set of series of instructions.第一组是名称列表,第二组是一系列指令。
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. 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.
For one it makes an array that looks like:一方面,它制作了一个如下所示的数组:
const listObj = [
{11/20/2020: [{name:'Joe', date:11/20/2020}]},
{11/26/2020 : [{name:'John', date:11/26/2020}]}
]
And this:和这个:
const scheduleObj = [
{11/20/2020: {type:'Federal', date:11/20/2020}},
{11/26/2020 : {type:'State', date:11/26/2020}}
]
The final product that i need would look something like:我需要的最终产品看起来像:
const scheduleObj = [
{11/26/2020 : {
type: 'State',
list: [{name:'John', date:11/26/2020}]
},
...
]
Where the list is an added key and the array is the array that is associated with the object key其中列表是添加的键,数组是与 object 键关联的数组
I have used a messy what looks like lodash
method to get this to work, but I figure there has to be some sort of mapping I can do.我使用了一种看起来像
lodash
的凌乱方法来让它工作,但我认为必须有某种我可以做的映射。
Any Help Would Be Appreciated任何帮助,将不胜感激
This can be little messy and not failure proof depending on what you have in your listObj
or scheduleObj
.根据您在
listObj
或scheduleObj
中的内容,这可能有点混乱,并且不是故障证明。 Eg repeated date in scheduleObj
can lead to a problem using this method, you may have to use another key
if the dates are no unique in both lists.例如,
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
}
};
})
Note that I'm always considering you have only one key in the objects inside the lists in listObj
or scheduleObj
.请注意,我一直认为您在
listObj
或scheduleObj
的列表中的对象中只有一个键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.