Skip to content
Advertisement

Check array for length and push or update the object within

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement