How to compare 2 Arrays to update key value pairs in one?

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

I have a main array of tags

var tagsArray = [     {         name: "1",         selected: undefined     },     {         name: "2",         selected: undefined     },     {         name: "3",         selected: undefined     } ] 

Then an array of selected tags to compare it to:

var selectedTags = [     {         name: "1",         selected: true     } ] 

How would you run some kind of comparison (for-loop) to check what objects in selectedTags have the selected: true value?

Then also set the same object's selected value in tagsArray to true?

回答1:

Create an access map, then iterate and find the true values and set the values in the other array

var map = {};  tagsArray.forEach(function(obj, index) {     map[obj.name] = index; });  selectedTags.forEach(function(obj) {     if ( obj.selected ) {         tagsArray[map[obj.name]].selected = true;     } }); 

FIDDLE



回答2:

You can still use 2 for-loops and it doesn't look much worse in terms of code or clarity. But on average it will run slower O(n^2) than using map.

var i,j;  for(i = 0; i < tagsArray.length; i++){     for(j = 0; j < selectedTags.length; j++){         if(tagsArray[i].name === selectedTags[j].name){             tagsArray[i].selected = true;             break;         }     } } 

JS Fiddle



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!