How to update the value of other duplicate objects in array of object, if one of the duplicate item is updated

Viewed 225

From below object I have concatenated all "roles" key value:

{
    "office1": {
        "roles": [
            {
                "name": "Test 0",
                "email": "test0@test.com"
            },
            {
                "name": "Test 1",
                "email": "test1@test.com"
            },
            {
                "name": "Test 2",
                "email": "test2@test.com"
            },
            {
                "name": "Test 3",
                "email": "test3@test.com"
            }
        ]
    },
    "office2": {
        "roles": [
            {
                "name": "Test 3",
                "email": "test3@test.com"
            },
            {
                "name": "Test 4",
                "email": "test4@test.com"
            },
            {
                "name": "Test 5",
                "email": "test5@test.com"
            }
        ]
    }
}

so new concatenated array "combinedRoles" look like below, which have duplicate values (e.g. {"name": "Test 3", "email": "test3@test.com"}. I want to update all other duplicate objects in the array, if any one of the object is updated out of all duplicate objects. In below example array element 3 and 4 have similar value, so if I update the element 3 it should update element 4 as well or vice versa.

combinedRoles = [
    {
        'name': 'Test 0',
        'email': 'test0@test.com'
    },
    {
        'name': 'Test 1',
        'email': 'test1@test.com'
    },
    {
        'name': 'Test 2',
        'email': 'test2@test.com'
    },
    {
        'name': 'Test 3',
        'email': 'test3@test.com'
    },
    {
        'name': 'Test 3',
        'email': 'test3@test.com'
    },
    {
        'name': 'Test 4',
        'email': 'test4@test.com'
    },
    {
        'name': 'Test 5',
        'email': 'test5@test.com'
    }
]
1 Answers

If the objects that need to be updated together are always exactly the same, creating an array of references rather than using object literals might work.

const obj0 = {'name': 'Test 0',
    'email': 'test0@test.com'
}
const obj1 = {'name': 'Test 1',
    'email': 'test1@test.com'
}
const obj2 = {'name': 'Test 2',
    'email': 'test2@test.com'
}
const obj3 = {'name': 'Test 3',
    'email': 'test3@test.com'
}

obj = [obj0, obj1, obj2, obj3, obj3]

Now obj[3] and obj[4] are two references to the same object, so anything you do to it will affect both references in the array:

obj[3].email = "foo"
console.log(obj[4].email) // "foo"

If the objects aren't always the same, then you could write a function to loop through the array, find every matching object, and update them manually, but that would depend on how you define two matching objects.

Related