Check if object value exists within a Javascript array of objects and if not add a new object to array

Andyuser2576960提出了一个问题:Check if object value exists within a Javascript array of objects and if not add a new object to array,或许与您遇到的问题类似。

回答者Andy给出了该问题的处理方式:

I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:

function checkAndAdd(name) {
  var id = arr.length + 1;
  var found = arr.some(function (el) {
    return el.username === name;
  });
  if (!found) { arr.push({ id: id, username: name }); }
}

Fiddle

希望本文对你有帮助,欢迎支持JavaScript中文网