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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With