Search code examples
javascriptlodash

Finding values differences for objects of arrays


I have two arrays, both of they consists of random keys and values. I have an updated object and current object. But the updated object contains new values and old values. I want to find the differences between those two objects keys and values, to produce the new updated object with new keys or values.

Current Object

{
  key1: "abc"
  key2: "ggg"
  key3: 0,
  key4: ["1","3","5"]
  key5: [1,2,3,4,5]
  key6: [9,8,7,6],
  key7: false
}

Updated Object

{
  key1: "abc"
  key2: "new"
  key3: 30,
  key4: ["1","3","5"]
  key5: [2,3,4]
  key6: [],
  key7: true,
  special8: [1,2,3]
}

Result

{
  key2: "new"
  key3: 30,
  key5: [2,3,4]
  key6: [],
  key7: true,
  special8: [1,2,3]
}

Solution

  • Given your conditions: the following reduce() function compares each of your updated object's properties against each of your current object's properties and returns a brand new object containing the differences.

    Please note: simply shallowly comparing arrays of strings (such as your key4 properties) using !== can return false negatives, hence the use of JSON.stringify().

    // Current Object.
    const current = {
      key1: "abc",
      key2: "ggg",
      key3: 0,
      key4: ["1","3","5"],
      key5: [1,2,3,4,5],
      key6: [9,8,7,6],
      key7: false
    }
    
    // Updated Object.
    const updated = {
      key1: "abc",
      key2: "new",
      key3: 30,
      key4: ["1","3","5"],
      key5: [2,3,4],
      key6: [],
      key7: true,
      special8: [1,2,3]
    }
    
    // Difference Object.
    const difference = (Object.keys(updated)).reduce((difference, key) => {
    
      // Same?
      if (JSON.stringify(updated[key]) == JSON.stringify(current[key])) return difference 
    
      // Different.
      return {...difference, [key]: updated[key]}
    
    }, {})
    
    console.log(difference)