vue3 two-way bind nested json best practice

Viewed 64

i have the following JSON response from a REST API

{
"data": {
    "name": "data 123",
    "prop1" : "abc",
    "prop2" : "xyz",
    "contacts": [
        {
            "id" : 1
            "name": "person 1",
            "address": {
                "city": "London",
                "zipcode": "1234",
                "street": "Demostreet",
                "housenumber": "123"
            }
        },
        {
            .....
        }
    ]
}

}

now let's say i want to bind the first contact's ZIPCODE to a input field. from my point of view i've got two options:

write a computed property with a setter and a getter for the input v-model for EVERY property in the JSON that i want to be editable for the user so that i can simply send back the same JSON

aka something like that

computed: {
    zipcode: {
        get(){
            let contact = this.form.contacts?.find(f => f.id == 1);
            if (contact != undefined)
                return contact.address.zipcode;
            else
                return "";
        },
        set(val){
            let contact = this.form.contacts?.find(f => f.id == 1);
            contact.address.zipcode = val;
        }

    }
}

or write a simplified local flattenend down JSON - bind it directly to the input v-model and map it to the received JSON when clicking SAVE.

{
"data":{
    "name": "data 123",
    "prop1" : "abc",
    "prop2" : "xyz",
    "city1": "London",
    "zipcode1": "1234",
    "street1": "Demostreet",
    "housenumber1": "123"
}
}

what's the best practice for such deep nested json two way binding? am i missing something?

i don't like both options

0 Answers
Related