Hi everyone, thank you very much in advance.
I am trying to compare two arrays of objects, what I want to achieve is that if the id property coincides in both objects, add a new element "selected" with the property true to my first array of objects, I already have something set up and it works more, however it does not I feel that it is the best way since when performing a console.log in the forEach iteration I see that the elements are iterated more times than they should be.
I share my code to make myself understand better:
My first array:
optionsSelect = [
{ id:14, isActive:true, name:"rfc", value:"rfc" },
{ id:15, isActive:true, name:"nombre completo", value:"full_name" },
{ id:16, isActive:true, name:"curp", value:"curp" }
];
My second array:
templateSettings = [
{ id:14, isActive:true, name:"rfc", value:"rfc"},
{ id:15, isActive:true, name:"nombre completo", value:"full_name"}
];
My solution:
optionsSelect = [
{ id:14, isActive:true, name:"rfc", value:"rfc" },
{ id:15, isActive:true, name:"nombre completo", value:"full_name" },
{ id:16, isActive:true, name:"curp", value:"curp" }
];
templateSettings = [
{ id:14, isActive:true, name:"rfc", value:"rfc"},
{ id:15, isActive:true, name:"nombre completo", value:"full_name"}
];
optionsSelect.forEach(element => {
templateSettings.forEach(item => {
//console.log("--------------")
//console.log(item)
//console.log("--------------")
if(element.id === item.id) {
element.selected = true
}
})
})
console.log('resultado optionSelect', optionsSelect)
If you uncomment the console.log, you will see what I mean, any way to optimize the code?