2

Say i have two objects, object_one

{
  1: {item1 /*updated*/}, //note updated represents more recent item1 data
  2: {item1 /*updated*/},
  3: {item1 /*updated*/}
}

and object_two

{
  1: {item1, item2, item3},
  2: {item1, item2, item3},
  4: {item1, item2, item3},
  5: {item1, item2, item3}
}

I want to add the object_one into the object_two, adding any elements that the object_two doesn't have. I also want to take the object_two's versions of item1 and update them to the value of object_one's

Desired result

{
  1: {item1 /*updated*/, item2, item3},
  2: {item1 /*updated*/, item2, item3},
  3: {item1 /*updated*/},
  4: {item1, item2, item3},
  5: {item1, item2, item3}
}

I've tried doing it myself, but my solution was manual and didn't work for all lengths of object_one and object_two. Some direction would be much appreciated

4
  • What does item1(updated) resolve to? Is that a function? Commented Apr 3, 2018 at 6:02
  • @CertainPerformance its just pseudo code, ment to represent that the smaller object's values are more recent Commented Apr 3, 2018 at 6:02
  • the question is how can we think item1(updated)===item1 so item1(updated) don't need to update?because they both have string item1? Commented Apr 3, 2018 at 6:05
  • updated question @xianshenglu Commented Apr 3, 2018 at 6:07

1 Answer 1

3

See Object.entries and Object.assign for more info.

// Original.
const original = {
  1: {A: '1A', B: '1B', C: '1C'},
  2: {A: '2A', B: '2B', C: '2C'},
  4: {A: '4A', B: '4B', C: '4C'},
  5: {A: '5A', B: '5B', C: '5C'}
}

// Merge.
const update = {
  1: {A: '1A updated'},
  2: {B: '2B updated'},
  3: {C: '3C updated'}
}

// Combine.
const merge = (original, update) => {
  const x = {...original}
  Object.entries(update).forEach(([key, value]) => {
    x[key] = Object.assign({}, x[key], value)
  })
  return x
}

// Output.
const output = merge(original, update)

// Proof.
console.log(output)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.