Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add multiple javascript objects with the same key to an associative array?

I am working on a Javascript web application (SPA) with RESTful api on the back-end. In my client-side datacontext I want to add objects to my model graph and then send the whole graph to server at once.

Suppose the following example:

I have a Person object in my model which itself has an array of say PhoneNumbers as a property. Now I load a Person from api for edditing and map it to my model. Suppose I want to add some phone number objects to my PhoneNumbers. For this I add each number e.g. {"id": 0, "number": 6536652226} with an id of zero to my client model and send the whole graph to server when user clicks save. In server I add the objects with the id of zero (new objects) to database with auto-incremented ids.

I am doing my project based on a tutorial. They do something like this to add objects to context:

                var items = {},
                    // returns the model item produced by merging json obj into context
                    mapJsonToContext = function (json) {
                        var id = mapper.getJsonId(json);
                        var existingItem = items[id];
                        items[id] = mapper.fromDto(json, existingItem); //returns the mapped obj
                        return items[id];
                    },
                    add = function (newObj) {
                    items[newObj.id()] = newObj;
                    }

The problem is that if I use this method I wouldn't be able to remove by id the newly-added-not-yet-saved items in client-side 'cause all the ids are zero!

Any suggestions to fix this, or do I need a totally different approach?

like image 528
Pejman Avatar asked Mar 21 '26 03:03

Pejman


1 Answers

First of all, two little misconceptions I've spot:

1) Forget about "associative arrays". Numeric arrays are the only kind arrays you have; the other constructs are just "objects" (this is not PHP).

2) If it's JSON it's a string, not an object.

Other than that, you can of course use an arbitrary value to represent "new" (though I'd probably use null rather than 0) as soon as you don't use such value to uniquely identify the yet-to-add item. E.g., this is just fine:

[
    {"id": 0, "number": "6536652226"},
    {"id": 0, "number": "9876543210"},
    {"id": 0, "number": "0123456789"}
]

This is not:

// WRONG!!!!
{
    0: "6536652226",
    0: "9876543210",
    0: "0123456789"
}

}

And of course you cannot find numbers by ID if they still don't have an ID. You need to choose:

  • Retrieve the generated ID from DB and update your local data
  • Delete by number
like image 194
Álvaro González Avatar answered Mar 23 '26 17:03

Álvaro González



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!