Let's say I have the following two Javascript objects:
let platformModules = [
{
id: 1,
name: 'Module One',
icon: 'icon-01',
deleted: false
},
{
id: 3,
name: 'Module Two',
icon: 'icon-02',
deleted: false
}
]
and
let companyModules = [
{
id: 1,
companyId: 4,
name: 'Our second module',
enabled: true,
position: 2
},
{
id: 3,
companyId: 4,
name: 'Our first module',
enabled: true,
position: 1
}
]
What I'd like to be able to do is to take the icon key (and it's value)
from platformModules and insert it into a new object based on companyModules, like the example below:
let displayModules = [
{
id: 1,
companyId: 4,
name: 'Our second module',
enabled: true,
position: 2,
icon: 'icon-01'
},
{
id: 3,
companyId: 4,
name: 'Our first module',
enabled: true,
position: 1,
icon: 'icon-01'
}
]
I have tried the follow, but it is not working:
function findAndMerge (source, target, findKey) {
for (var key in source) {
if (source.hasOwnProperty(key) && source[key] === findKey) {
target[key] = source[key]
}
}
}
let displayModules = findAndMerge(platformModules, companyModules, icon)
Any help, pointers would be greatly appreciated. Many thanks.
source[key] === findKey- if you're passing in thekey- shouldn't it bekey === findKey- also what is not working? What isiconin your case when you call this method?platformModules.map((object, index) => ({ ...object, ...companyModules[index] })). Of course, you will need to ensure that the elements at the indexes have the same id...