0

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.

2
  • source[key] === findKey - if you're passing in the key - shouldn't it be key === findKey - also what is not working? What is icon in your case when you call this method? Commented Dec 21, 2017 at 16:25
  • 1
    platformModules.map((object, index) => ({ ...object, ...companyModules[index] })). Of course, you will need to ensure that the elements at the indexes have the same id... Commented Dec 21, 2017 at 16:25

1 Answer 1

0

Use Array's map() to loop through the base array (companyModules) and then assign the object from platformModules by using Object.assign(). Try the following:

let platformModules = [
  {
    id: 1,
    name: 'Module One',
    icon: 'icon-01',
    deleted: false
  },
  {
    id: 3,
    name: 'Module Two',
    icon: 'icon-02',
    deleted: false
  }
]

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
  }
]

var displayModules = companyModules.map(function(item, i){
  return Object.assign({'icon':platformModules[i].icon},item);
});
console.log(displayModules);

Sign up to request clarification or add additional context in comments.

2 Comments

Yup, thanks, that did the job nicely. Much appreciated.
@NeilMerton, you are most welcome.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.