Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only add if not already in place

Here's my data structure:

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

The id value should be unique, but the info may not be unique. How would I add new data into the data hash only if the id of the new data is unique?

Is the only way to iterate over the whole hash and see if there is such an id already in place?

data.push({ id: '1967', info: 'goo-goo' }); //should not be added
data.push({ id: '1963', info: 'goo-goo' }); //should be added
like image 296
Woppie Avatar asked Dec 15 '25 10:12

Woppie


1 Answers

If you can change your data structure, it 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 benefit of being a lot faster to access (if you have the ID).

like image 191
Ivo Wetzel Avatar answered Dec 17 '25 00:12

Ivo Wetzel



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!