Search code examples
javascriptecmascript-5

Comparing 2 objects and making alterations based on Match


I have 2 objects with key-value pairs that should always be identical (match) otherwise I want to modify the value of the key in object #1 to "Some Value - Not available"

Here are my 2 objects:

Object #1

[
  {
    "name": "John",
    "age": "12",
    "id": 1
  },
  {
    "name": "tina",
    "age": "19",
    "id": 2
  }]

Object #2 ( name checker)

 [
      {
        "value": "tina"
      },
      {
        "value": "Trevor"
      },
      {
        "value": "Donald"
      },
      {
        "value": "Elon"
      },
      {
        "value": "Pamela"
      },
      {
        "value": "Chris"
      },
      {
        "value": "Jackson"
      }
    ]

I would like to find out if name in Object #1 is found in Object #2 and if it is not found, add " - not available"

e.i

[
      {
        "name": "John - not available",
        "age": "12",
        "id": 1
      },
      {
        "name": "tina",
        "age": "19",
        "id": 2
      }
]

Important Note: I'm using ES5 --- not ES6


Solution

  • This should work in ES5

    object1.forEach(function(person) {
      var found = false;
      Object.keys(object2).forEach(function(key) {
        if (person.name === object2[key].value) {
          found = true;
        }
      });
      if (!found) {
        person.name = person.name + " - not available";
      }
    });