diff --git a/audit/audit.go b/audit/audit.go index 1ff39abc6c3af2287b77db1dd50bfb58970b2442..2b466673a235669d3a5488cd004396484ca4f54e 100644 --- a/audit/audit.go +++ b/audit/audit.go @@ -63,9 +63,10 @@ func GetChanges(original interface{}, new interface{}) (map[string]interface{}, arrayObject, present := changes[objectKey] if present { if arrayOfObjects, ok := arrayObject.([]map[string]interface{}); ok { - if len(arrayOfObjects) > int(index) { + arrayIndex := ArrayIndexForObjectIndex(arrayOfObjects, index) + if arrayIndex != -1 { // Add field to existing object in array - object := arrayOfObjects[index] + object := arrayOfObjects[arrayIndex] object[field] = FieldChange{ From: change.From, To: change.To, @@ -73,6 +74,7 @@ func GetChanges(original interface{}, new interface{}) (map[string]interface{}, } else { // new object, append to existing array fieldChange := map[string]interface{}{ + "index": index, field: FieldChange{ From: change.From, To: change.To, @@ -85,6 +87,7 @@ func GetChanges(original interface{}, new interface{}) (map[string]interface{}, } else { // Create array of objects fieldChange := map[string]interface{}{ + "index": index, field: FieldChange{ From: change.From, To: change.To, @@ -124,6 +127,20 @@ func ChildObjectChanges(changes map[string]interface{}, objectPath string, field } } +// ArrayIndexForObjectIndex gets the index of arrayOfObjects where the object's index field is equal to objectIndex. +func ArrayIndexForObjectIndex(arrayOfObjects []map[string]interface{}, objectIndex int64) int { + for arrayIndex, object := range arrayOfObjects { + index, present := object["index"] + if present { + if index == objectIndex { + return arrayIndex + } + } + } + + return -1 +} + // GetAllChanges Returns the diff, structured in json, recursively // Be warned, here be dragons. Debug this first to understand how it works func GetAllChanges(original interface{}, new interface{}) (map[string]interface{}, error) {