Update on duplicate using javascript

I got two object arrays to compare and return a result which contains two arrays one for insert and one for update.

  • aObj --> parent object. (primary/unique key is empid)
  • bObj --> children object.(primary/unique key is empid)
let a = [
  { empid: "emp001", name: "test1", status: "emp" },
  { empid: "emp002", name: "test2", status: "ex-emp" },
  { empid: "emp003", name: "test3", status: "emp" }
];

let b = [
  { empid: "emp001", name: "test1_updated", status: "emp" },
  { empid: "emp002", name: "test2", status: "emp" }
];

//insert array
// console.log(_.differenceBy(a, b, 'empid'));

//update array
let updateArr = [],
  insertArr = [];
for (let i = 0; i < a.length; i++) {
  let aObj = a[i];
  for (let j = 0; j < b.length; j++) {
    let bObj = b[j];
    if (aObj.empid === bObj.empid) {
      if (aObj.status !== bObj.status || aObj.name !== bObj.name) {
        updateArr.push(aObj);
      }
    } else {
      insertArr.push(aObj);
    }
  }
}
console.log("--update--");
console.log(updateArr);
console.log("--insert--");
console.log(insertArr);

Code Links - https://codesandbox.io/s/fervent-kare-ixht9?fontsize=14&hidenavigation=1&theme=dark



from Recent Questions - Stack Overflow https://ift.tt/3jggeCF
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations