1

I'm using dep-object-diff, which returns differences between two objects.

The problem is that if I have something like,

const objectA = {
  fieldA: 5,
  fieldB: ['123']
}
const objectB = {
  fieldA: 5,
  fieldB: ['123', '456']
}

Then it returns,

const diff = {
  fieldB: {
    0: '456'
  }
}

When the required response object should be,

const diff = {
  fieldB: ['456']
}

How can I detect if diff.fieldB is an array (dynamically, without hardcoding), and consequently convert it into one?


Edit

Thanks to @Nina Scholz, I ended up using her approach as the base. The problem which I caught with my data, however, was that the approach didn't work for strings. Anyway, I ended up implementing it as follows:

const diffs = {
  fieldA: "SOME_STRING",
  fieldB: {
    3: '123',
    5: '456'
  },
};

const chronologize = (object) => {
  let counter = 0;

  for (let prop in object) {
    if (object[prop]) {
      object[counter] = object[prop];
      delete object[prop];
      counter++;
    }
  }

  return object;
};

const result = Object.fromEntries(
  Object.entries(diffs).map(([k, v]) =>
    typeof v === 'string'
      ? [k, v]
      : [k, Object.assign([], chronologize(v))]),
);

console.log(result);

2
  • what should happen, if you have no array like object? Commented Apr 16, 2020 at 12:05
  • 1
    Well, the object may contain properties the have values that are arrays or strings. Your answer worked brilliantly for the use case I posted, but sometimes the diff object can be const diff = { fieldA: 10, fieldB: { 3: '456' } }, where fieldB.length === 4. This means that fieldA changed and that fieldB also changed -- the change in fieldB being an addition of an element to the array. I worked around this, however, using your approach as a base. I had to do several more transformations, such as making sure it's { 0: '456' } and not { 3: '456' }, but that's ok, I think. Commented Apr 16, 2020 at 12:18

1 Answer 1

1

You could get the entries, convert the array like object to array with Object.assign and an array as target and convert back to an object.

const 
    diff = { fieldB: { 0: '456' } },
    result = Object.fromEntries(Object.entries(diff).map(([k, v]) => [k, Object.assign([], v)]));

console.log(result);

Sign up to request clarification or add additional context in comments.

2 Comments

Hello, sorry, I know this wasn't asked, but what if it's const diff = { fieldA: 'someString', fieldB: { 0: '456' } }?
the result is funny, you get single letters for a string value. { "fieldA": [ "s", "o", "m", "e", "S", "t", "r", "i", "n", "g" ], "fieldB": [ "456" ] }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.