简体   繁体   中英

Constructing a JavaScript Array prototype method

I am new to constructing a JavaScript Array prototype. Please only paste previous links that are directly appropriate as I have been sourcing on SO and on w3school. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype

I would like to create a method for an array that checks if the 'id' field within the object does not already exist in the array. If not, then 'push' object into the array, else do nothing.

Each object has a unique 'id' field.

eg

var array = [{ id: 001, title: 'some title'},
               { id: 002, title: 'other title'}]

var object = {id: 001, title: 'some title'}


// if object.id does not exist in array...
array.push(object)
//else do nothing

I would like the function to take the 'id' field as an argument so this function has wider use.

Are there any drawbacks to extending the array.Prototype? Otherwise I can do a for loop instead to do the check without the prototype constructor.

Since your ids are integers you could just set that index in the array directly.

var array = [];
var object = {id: 001, title: 'some title'};
array[object.id] = object;

That will overwrite the element in that location such that you won't get duplicates with the same id. Your js engine will automatically switch to using a sparse array rather than a contiguous array if your ids are far apart.

Instead of trying to change the behavior of Array consider using an object instead of array with the id as the key.

var objects = {};
var object = {id: 001, title: 'some title'}
objects[object.id] = object;

That way you can also retrieve your objects from the parent object by their id. eg

var result = objects[001];

I found brads's answer using the function containsObject How do I check if an array includes an object in JavaScript?

This does a check so there is no extra writes to the database such as overwrites. Thank you everyone for inputting towards the question. It has helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM