如果匹配 ID,则合并数组并为其添加标志
Posted
技术标签:
【中文标题】如果匹配 ID,则合并数组并为其添加标志【英文标题】:Combine arrays and add flag to it if matches the ID 【发布时间】:2022-01-15 10:14:09 【问题描述】:我有两个结构相同的数组。
let TaskArray=[
"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3",
"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3",
"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3",
"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3",
"TaskID:"167","TaskName":"task5","TaskGroup":"group","UserID":"3",
"TaskID:"166","TaskName":"task6","TaskGroup":"group","UserID":"3",
"TaskID:"165","TaskName":"task7","TaskGroup":"group","UserID":"3",
"TaskID:"164","TaskName":"task8","TaskGroup":"group","UserID":"3",
"TaskID:"163","TaskName":"task9","TaskGroup":"group","UserID":"3",
"TaskID:"162","TaskName":"task10","TaskGroup":"group","UserID":"3"
]
let TaskDetailsArray = [
"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3",
"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3",
"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3",
"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3",
]
如果通过第一个数组中的 id 找到第二个数组中的项,我需要比较两个数组并将标志 isAssigned 设置为 true,否则设置为 false。
matcheArray = [
"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3",isAssigned: true,
"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3",isAssigned: true,
"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3",isAssigned: true,
"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3",isAssigned: true,
"TaskID:"167","TaskName":"task5","TaskGroup":"group","UserID":"3",
"TaskID:"166","TaskName":"task6","TaskGroup":"group","UserID":"3",
"TaskID:"165","TaskName":"task7","TaskGroup":"group","UserID":"3",
"TaskID:"164","TaskName":"task8","TaskGroup":"group","UserID":"3",
"TaskID:"163","TaskName":"task9","TaskGroup":"group","UserID":"3",
"TaskID:"162","TaskName":"task10","TaskGroup":"group","UserID":"3"
]
下面的代码工作正常,但我不确定是否有更好的方法来完成它。请提出建议。
for (var i = 0; i < TaskArray.length; i++)
for (var k = 0; k < this.TaskDetailsArray.length; k++)
if (TaskArray[i].TaskID == this.TaskDetailsArray[k].TaskID)
if (!this.TaskDetailsArray[k].isAssigned)
this.TaskDetailsArray[k].isAssigned = true;
;
【问题讨论】:
sn-p 不仅仅是一个更好的代码块。仅在可以执行其内容并为问题添加某些内容(例如产生您正在谈论的错误)的情况下才使用 sn-p。 请修复损坏的语法(通过损坏的语法突出显示可见) 【参考方案1】:const comparedArray = taskArray.map(item =>
return
...item,
isAssigned: TaskDetailsArray.some(secondItem => secondItem.TaskId === item.TaskId );
)
【讨论】:
以上是关于如果匹配 ID,则合并数组并为其添加标志的主要内容,如果未能解决你的问题,请参考以下文章