Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Arrays returned as objects #94

Open
StephenTHendrix opened this issue Mar 28, 2023 · 6 comments
Open

Arrays returned as objects #94

StephenTHendrix opened this issue Mar 28, 2023 · 6 comments

Comments

@StephenTHendrix
Copy link

I think I'm just re-reporting #79.

diff({ test: [] }, { test: ['apple'] })
returns
{ test: { 0: 'apple' }

@obrunopolo
Copy link

Same for me

@mikila85
Copy link

same for me, is there a fix anyone found or should i find a different package?
actually should even be ability to say ignoreArrays:true to just get the new array instead of each index which doesnt really matter to alot of people..

@baermathias
Copy link

It seems that this here doesn't work at all:

  diff(
    {
      v: {
        data: [
          {
            blabla: 3,
          },
        ],
      },
    },
    {
      v: {
        data: [
          {},
        ],
      },
    },
  ),

Returns:

[Object: null prototype] {
  v: [Object: null prototype] {
    data: [Object: null prototype] { '0': [Object: null prototype] }
  }
}

@MarlonFauser
Copy link

Same issue here!

@meszaros-lajos-gyorgy
Copy link

Did anyone find any alternatives to this repo that doesn't have this bug?

@meszaros-lajos-gyorgy
Copy link

meszaros-lajos-gyorgy commented Mar 7, 2025

Here's my current workaround:

import { diff } from 'deep-object-diff'

function isPlainObj(obj: any): boolean {
  return Object.prototype.toString.call(obj) === '[object Object]'
}

function isPositiveInteger(value: string): boolean {
  const n = Number.parseInt(value, 10)
  return Number.isInteger(n) && n >= 0
}

function isArrayLooking(obj: object): boolean {
  return Object.keys(obj).every((key) => {
    return isPositiveInteger(key)
  })
}

function fix(data: any) {
  if (isPlainObj(data)) {
    if (isArrayLooking(data)) {
      data.length = Object.keys(data).length
      data = Array.from(data)
      return data.map((value) => {
        return fix(value)
      })
    } else {
      let kvPairs = Object.entries(data)
      kvPairs = kvPairs.map(([key, value]) => {
        return [key, fix(value)]
      })
      return Object.fromEntries(kvPairs)
    }
  } else {
    return data
  }
}

// -----------

const oldData = ...
const newData = ...

const patch = fix(diff(oldData, newData))

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants