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);
const diff = { fieldA: 10, fieldB: { 3: '456' } }, wherefieldB.length === 4. This means thatfieldAchanged and thatfieldBalso changed -- the change infieldBbeing 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.