Only add if not already installed

Here is my data structure:

var data = [
 { id: '1924', info: 'boo' },
 { id: '1967', info: 'foo' }
];

The id value must be unique, but the information may not be unique. How to add new data to the hash data only if the unique identifier of the new data is unique?

Is the only way to iterate over the entire hash and see if such an identifier is already in place?

data.push({ id: '1967', info: 'goo-goo' }); //should not be added
data.push({ id: '1963', info: 'goo-goo' }); //should be added
+3
source share
2 answers

If you can change the data structure, this can be done with less code:

var data = {
    '1924': {'info': 'goo-goo'},
    '1967': {'info': 'boo-boo'}
};

function add(obj, id, data) {
    if (obj[id] === undefined) { // if you have fear about the prototype chain being poisoned
                                 // add in a hasOwnProperty
        obj[id] = data;
    }
}

This will also have the advantage of being much faster for access (if you have an ID).

+9
source

Ivo, , . { id: '1967', info: 'foo' } 1 , data[1], .

-1

Source: https://habr.com/ru/post/1783062/


All Articles