-4

So here i have two object data:

{
    "obj1": {
        "product": "Book",
        "category": "sci-fi",
        "title": "interstellar",
    },
    "obj2": {
        "product": "Book",
        "category": "horror",
        "title": "evil dead",                    
    },
   "differences": []
}

From that data, i need to comparing each value from obj1 and obj2 variables find keys that have difference values from these two objects then pushing it into differences variable.

Expected Result:

{
    "obj1": {
        "product": "Book",
        "category": "sci-fi",
        "title": "interstellar",
    },
    "obj2": {
        "product": "Book",
        "category": "horror",
        "title": "evil dead",                    
    },
   "differences": [
        "category",
        "title"
   ]
}

Does anyone have recommendation to solving it?

adiga
  • 34,372
  • 9
  • 61
  • 83
kammaaal
  • 1
  • 1
  • What have you tried so far? – Harun Yilmaz Jan 10 '23 at 08:12
  • Please visit the [help], take the [tour] to see what and [ask]. Do some research - [search SO for answers](https://www.google.com/search?q=javascript+object+diff+site%3Astackoverflow.com). If you get stuck, post a [mcve] of your attempt, noting input and expected output using the [\[<>\]](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Jan 10 '23 at 08:21

1 Answers1

0

You can simply make 2 loop, one for each object and then compare by key :

let data = {
  "obj1": {
    "product": "Book",
    "category": "sci-fi",
    "title": "interstellar",
  },
  "obj2": {
    "product": "Book",
    "category": "horror",
    "title": "evil dead",
  },
  "differences": []
};

for (let key1 in data.obj1) {
  for (let key2 in data.obj2) {
    if (key1 === key2 && data.obj1[key1] !== data.obj2[key2]) {
      data.differences.push(key1);
    }
  }
}
console.log(data);
Johan
  • 2,088
  • 2
  • 9
  • 37