Home > Enterprise >  Js update object by another object but ignore columns don't exists in the first object
Js update object by another object but ignore columns don't exists in the first object

Time:01-19

How to update an object by another object then ignore the columns don't exist in the object?

Let say I have 2 objects

Object A:

[
  {
    "title": "herry patter",
    "actors": [
      {
        "name": "Harry",
        "feature": "lighting"
      },
      {
        "name": "Ron",
        "feature": "Red"
      }
    ]
  }
]

Object B

[
  {
    "title": "harry potter",
    "nothingHere": "bybye",
    "actors": [
      {
        "name": "Harry Potter",
        "feature": "lighting Scar"
      },
      {
        "name": "Hermione",
        "feature": "smart"
      }
    ]
  }
]

After the processing, the Object should be updated by the existing field, but it ignore the unexpected field that is missing from the object A.

Result:

[
  {
    "title": "harry potter",
    "actors": [
      {
        "name": "Harry Potter",
        "feature": "lighting Scar"
      },
      {
        "name": "Hermione",
        "feature": "smart"
      }
    ]
  }
]

CodePudding user response:

You can map the items from a, and for each item, reduce the keys into a new object by referencing the corresponding value based on the current index of the b array.

const
  a = [{
    "title": "herry patter",
    "actors": [
      { "name": "Harry", "feature": "lighting" },
      { "name": "Ron", "feature": "Red" }
    ]
  }],
  b = [{
    "title": "harry potter",
    "nothingHere": "bybye",
    "actors": [
      { "name": "Harry Potter", "feature": "lighting Scar" },
      { "name": "Hermione", "feature": "smart"  }
    ]
  }],
  c = a.map((item, index) =>
    Object.keys(item).reduce((acc, key) =>
      ({ ...acc, [key]: b[index][key] }), {}));

console.log(c);
.as-console-wrapper { top: 0; max-height: 100% !important; }

CodePudding user response:

const a = [{"title":"herry patter","actors":[{"name":"Harry","feature":"lighting"},{"name":"Ron","feature":"Red"}]}]
const b = [{"title":"harry potter","nothingHere":"bybye","actors":[{"name":"Harry Potter","feature":"lighting Scar"},{"name":"Hermione","feature":"smart"}]}]

const f = (a,b) => Array.isArray(a) ? a.map((e,i)=>f(e,b[i])) :
  Object.fromEntries(Object.entries(a).map(([k,v])=>
    [k, b[k]!==undefined ? (v instanceof Object ? f(v, b[k]) : b[k]) : v]))

console.log(f(a,b))

This approach uses deep inspection, and so it doesn't simply replace an entire 'actors' array with another. It goes deep, and checks each item within the each of the 'actors' arrays.

  • Related