我需要从另一个数组hexCode
这是我正在过滤的数据
{
dateCreated: "2019-10-30 08:29:54 PM"
hexCode: "#ed4c67"
id: 1
leaveTag: "Vacation Leave"
leaveTagColor: "Bara Red"
}
{
dateCreated: "2019-10-30 08:30:05 PM"
hexCode: "#ea2027"
id: 2
leaveTag: "Sick Leave"
leaveTagColor: "Red Pigment"
}
这是我要插入hexCode的数据。然后映射leaveType
以将其与上面的数据进行比较。可以吗?
{
leaveType: "Emergency Leave"
email: "sfe.bruce.logan@gmail.com"
hexCode: ???
}
{
leaveType: "Sick Leave"
email: "sfe.bruce.logan@gmail.com"
hexCode: ???
}
答案 0 :(得分:0)
您可以像下面这样简单地进行查找,但是在这种情况下,时间复杂度更高(尽管可读性更高,并且没有空间复杂度)
或者您可以从第一个数据数组创建类型为leaveType : hexCode
的Map,然后使用Map查找相应的值并填充第二个数组。请检查@CodeManiac的答案是否适用。
const data = [{
dateCreated: "2019-10-30 08:29:54 PM",
hexCode: "#ed4c67",
id: 1,
leaveTag: "Vacation Leave",
leaveTagColor: "Bara Red"
},
{
dateCreated: "2019-10-30 08:30:05 PM",
hexCode: "#ea2027",
id: 2,
leaveTag: "Sick Leave",
leaveTagColor: "Red Pigment"
}]
const arr = [{
leaveType: "Emergency Leave",
email: "sfe.bruce.logan@gmail.com",
},
{
leaveType: "Sick Leave",
email: "sfe.bruce.logan@gmail.com"
}]
arr.forEach(leave => {
const matchedLeave = data.find(lv => lv.leaveTag === leave.leaveType);
if(matchedLeave) {
leave.hexCode = matchedLeave.hexCode;
}
});
console.log(arr);
答案 1 :(得分:0)
您可以使用Map
和map
leaveTag
映射到各自的hexCode
leaveType
中是否存在Map
(如果存在),请使用Map
中的值,否则将其保留为原始值
const data = [{dateCreated: "2019-10-30 08:29:54 PM",hexCode: "#ed4c67",id: 1,leaveTag: "Vacation Leave",leaveTagColor: "Bara Red"}, {dateCreated: "2019-10-30 08:30:05 PM",hexCode: "#ea2027",id: 2,leaveTag: "Sick Leave",leaveTagColor: "Red Pigment",}]
const desiredFormat = [{leaveType: "Emergency Leave",email: "sfe.bruce.logan@gmail.com",hexCode: ''}, {leaveType: "Sick Leave",email: "sfe.bruce.logan@gmail.com",hexCode: ''}]
const mapper = new Map(data.map(({leaveTag,hexCode}) => [leaveTag, hexCode]))
const final = desiredFormat.map(({ hexCode, ...rest }) => {
return {
...rest,
hexCode: mapper.get(rest.leaveType) || hexCode
}
})
console.log(final)
答案 2 :(得分:0)
我只使用数组映射的方法
const obj1 = [{
dateCreated: "2019-10-30 08:29:54 PM",
hexCode: "#ed4c67",
id: 1,
leaveTag: "Vacation Leave",
leaveTagColor: "Bara Red"
},
{
dateCreated: "2019-10-30 08:30:05 PM",
hexCode: "#ea2027",
id: 2,
leaveTag: "Sick Leave",
leaveTagColor: "Red Pigment"
}]
const obj2 = [{
leaveType: "Emergency Leave",
email: "sfe.bruce.logan@gmail.com",
hexCode: null
},
{
leaveType: "Sick Leave",
email: "sfe.bruce.logan@gmail.com",
hexCode: null
}]
const result = obj2.map(item => {
const findedHex = obj1.find(o2item => o2item.leaveTag == item.leaveType)
item.hexCode = findedHex && findedHex.hexCode || null;
return item;
})
console.log(result)