0

I have two objects (some may call them dictionaries) which look like the following:

object1 = 
{
     id123: 
     {
           name: Copenhagen,
           type: 'city'
     }
}

object2 = 
{
     id123: 
     {
           name: Copenhagen,
           type: 'county',
           props: { id1: true, id: false}
     },
     id1234: 
     {
           name: Pars,
           type: 'county',
           props: { id1: true, id: false}
     },
     id12345: 
     {
           name: London,
           type: 'county',
           props: { id1: true, id: false}
     },
}

If two ids are the same, my merged object needs to take the type from object1, and needs to keep the props from object2, like so (notice Copenhagen):

mergedObjects = 
{
     id123: 
     {
           name: Copenhagen,
           type: 'city',
           props: { id1: true, id: false}
     },
     id1234: 
     {
           name: Pars,
           type: 'county',
           props: { id1: true, id: false}
     },
     id12345: 
     {
           name: London,
           type: 'county',
           props: { id1: true, id: false}
     },
}

I've tried the following with the spread operator:

mergedObjects = { ...object2, ...object1 }

But the whole id object is replaced, rather than merged. Can you help?

kingloui
  • 161
  • 3
  • 12
  • The dupe target is a little over the top for this type of objects. Just iterate over the properties of `object1`, check if the same property is in `object2` and store the `type` from `object1` in the corresponding property of `object2` – Andreas Jan 30 '20 at 17:35

1 Answers1

0

Go thru the object2 keys, add the values to merged and update type from object1 if they have otherwise use the type of object2.

const object1 = {
  id123: {
    name: 'Copenhagen',
    type: "city"
  }
};

const object2 = {
  id123: {
    name: 'Copenhagen',
    type: "county",
    props: { id1: true, id: false }
  },
  id1234: {
    name: 'Pars',
    type: "county",
    props: { id1: true, id: false }
  },
  id12345: {
    name: 'London',
    type: "county",
    props: { id1: true, id: false }
  }
};

const merged = {};
Object.keys(object2).forEach(key => {
  merged[key] = { ...object2[key], type: object1[key] ? object1[key].type : object2[key].type };
});

console.log(merged);
Siva K V
  • 10,561
  • 2
  • 16
  • 29
  • _"Go thru the object2 keys"_ - We need the info from `object1`, so why should we iterate over `object2` where (in this case) 2/3 of the properties are not relevant? – Andreas Jan 30 '20 at 17:41
  • @Andreas, As in question, merged object has to have "props" from object2 (and object1 does not have "props" key) and overlay the "type" from object1. This is what I assumed based on the questions expected output. – Siva K V Jan 30 '20 at 17:52