Add item to array or substitute it if it has the same id

Viewed 95

I have this array of objects

var source = [
  {id: 1, label: "one"},
  {id: 2, label: "two"},
  {id: 3, label: "three"}
];

I need to add an item or substitute it if it has the same id

var new_sub = {id: 1, label: "new label for one"};
var new_add = {id: 4, label: "four"};

source = myFunc(new_sub);
source = myFunc(new_add);

function myFunc(obj) {
  return (source.findIndex(x => x.id === obj.id) === -1) ? 
  source.concat(obj) : source.map((item) => {
    return (item.id === obj.id) ? obj : item;
  });
}

This code works perfectly, but is there a better way to do this? You can check my code to this snippit:

var source = [
      {id: 1, label: "one"},
      {id: 2, label: "two"},
      {id: 3, label: "three"}
    ];
var new_sub = {id: 1, label: "new label for one"};
var new_add = {id: 4, label: "four"};

source = myFunc(new_sub);
source = myFunc(new_add);

function myFunc(obj) {
  return (source.findIndex(x => x.id === obj.id) === -1) ? 
   source.concat(obj) : source.map((item) => {
     return (item.id === obj.id) ? obj : item;
    });
}

//PRINT
var html = "";
source.map((item) => {
 html += "<li>" + item.id + " - " + item.label + "</li>";
});
$("#resp").html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="resp">
</ul>

4 Answers
Related