I'm really struggling with my code and cannot find a way to make it work.

I need to check whether my array exists or its length is not 0 and then if there is an object with a specific value in it. If so then update it. If not then add it. Please see my code below:

```
const originals = [];

if (!originals || originals.length === 0) {
  originals.push({
    "name": "Michael",
    "age": 21,
    "gender": "male"
  });
} else {
  for (i = 0; i < originals.length; i++) {
    if (originals[i].name !== "Michael") {
      originals.push({
        "name": "Michael",
        "age": 21,
        "gender": "male"
      });
    }
    if (originals[i].name == "Michael" && originals[i].age == 21) {
      originals[i].age = 22;
    }
  }
  console.log(originals);
}

```

Many thanks for your help in advance.
['https://Stackoverflow.com/questions/66714870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647297/']
Use the `find()` method to look for an element with the name you want. If it's found, update it, otherwise add the new element.

There's no need to check the length of the array. If the array is empty, `find()` won't find it.

```
let mike = originals.find(({name}) => name == 'Michael');
if (mike) {
    if (mike.age == 21) {
        mike.age = 22;
    }
} else {
    originals.push({
        "name": "Michael",
        "age": 21,
        "gender": "male"
    });
}

```

This solution assumes names are unique. If there can be multiple `Michael` entries, you can use `filter()` instead of `find()` to return all of them.
Reading between the lines what I think you want to do is:

* If "Michael" is in the array. Then his age should be updated to 21, if he is 22 years old.
* If "Michael" is not in the array. Then add Michael with an age of 21.

There are some odd things in your code which makes no sense to me. For example you are checking for "Michael" in the array each time when iterating the array. This would mean that you insert a "Michael" for each entry that is not named "Michael". That doesn't make sense, does it?

I think this is what you want:

```js
function addOrUpdateMichael(array) {
  const michael = array.find((x) => x.name == "Michael");
  if (!michael) {
      array.push({
          "name": "Michael",
          "age": 21,
          "gender": "male"
      });
  } else if (michael.age == 22) {
      michael.age = 21;
  }
  return array;
}

const testArray1 = [];
console.log(addOrUpdateMichael(testArray1));

const testArray2 = [{
    "name": "Michael",
    "age": 21,
    "gender": "male"
}, {
    "name": "Tony",
    "age": 18,
    "gender": "male"
}];
console.log(addOrUpdateMichael(testArray2));

const testArray3 = [{
    "name": "Michael",
    "age": 22,
    "gender": "male"
}, {
    "name": "Bob",
    "age": 36,
    "gender": "male"
}];
console.log(addOrUpdateMichael(testArray3));
```