Constructing a JavaScript Array prototype method - javascript

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. e.g.
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.

Related

Nested object in Javascript array

JS noob here. I want to store a list of option for a dropdown in an array. I want a key to be associated with every value something like this
var newArray = [
{
key: "key",
val:({value:"val", label:"label"}, {value:"val",label:"label"})
}
]
The code above returns undefined when I try to read val. What is the solution? Thanks
var newArray = [
{
key: "key",
val:[{value:"val", label:"label"}, {value:"val",label:"label"}]
}]
The only thing i changed were parentheses () into [], because it's the thing that declares an array. Now, if you want to read the val key, you need to do this stuff.
You have an array named "newArray". It only has 1 element (which is also the first).
Now lets get the first element of the array by newArray[0]. Now you have accessed the object inside the array. Now you can read the the value by newArray[0].val. And now you have entered a new array, which elements you can read with newArray[0].val[0] and newArray[0].val[1]

Json array appending a object

i have pushed data to an array like this
this.data.push{'data': 'type',
'value': 'apple'}
and i want to append the value of that particular array's value object. I tried to do it like this
this.data[index].value.push = 'banana';
but it doesn't work?? I want to replace the value
Push is a function Array.push()
this.data[index].push('banana');
Adding items to arrays work like this in javascript:
this.data.push({'data': 'type', 'value': 'apple'});
However, given that your data is an object, you don't need to use push:
this.data[index].value = 'banana';
You can access a value from a javascript object directly.
Given that you have used string keys, you will probably have to do the following:
this.data[index]['value'] = 'banana';
Look at this for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
i have pushed data to an array like this
this.data.push{'data': 'type', 'value': 'apple'}
No! That does not work without getting a syntax error.
You could use
this.data.push({'data': 'type', 'value': 'apple'});
for inserting a new object at the end of the array data.
For changing a specific objects's property, you need to assign the new content, like
this.data[index].value = 'banana';
This takes an element and the property and assigns the new value 'banana' to it.
Please have a look to properties accessors for objects, like
object.property
object["property"]
make it
this.data[index].value = ['banana'];
since you need to replace the value of value attribute with an array.
If this needs to be repeated again then
Array.isArray(this.data[index].value) ? (this.data[index].value = ['banana']) : this.data[index].value.push('banana');
push takes a parameter of object, you must have pass this parameter in braces
this.data.push({'data': 'type', 'value': 'apple'})
to change value you can directly change field value
this.data[index].value = 'banana';
if you want to keep multiple values in value then make value an array as well.

how to achieve this array

I want to be able to save an array (if possible), so that I can get to an entry within it quickly and easily with a unique identifier, something like:
array structure:
[
1001:{loads of info},
1002:{loads more info}
]
and to get values like:
var info_i_want = array.1001;
I have the 'loads of info' part already in a json object, just need to built this new array?
I ask because at the moment I have to loop through each object in the array to check if its the one I want before I can do anything
If you want you can use numeric keys with an object literal (not the array notation you used above):
var obj = {
1001: { /* data */},
1002: { /* data */}
};
With numeric keys, you must use bracket notation to dereference; i.e:
obj[1001]; // *not* dot reference `obj.1001` which will not work
Hope this helps :)
EDIT
For reference read the Object section of Javascript Garden, specifically Accessing Properties
you can assume like this.
var arr = [
{1001: "loads of info"},
{1002: "loads more info"}
]
var info_i_want = arr[0].1001 // returns loads of info

Javascript Array Key Lookup

I'm sorry if this has been asked before, it's something that's difficult to search for...
I want to use a javascript Array to hold objects, with the key as the ID
for example, let's say I had a bunch of people who had different IDs
var people = new Array();
var person = {property: value}; // this is person ID 4
var people[4] = person;
I want to be able to then reference that user by saying, people[ID].propery
The problem is that the output of this array now would be;
null,null,null,null,object
Because it's expecting the keys to be 0,1,2,3,4
Am I being stupid or something? :-) We can do it for strings right, so why not non-sequential numbers?
What I'm trying to avoid is having to loop over every single object in the array every time I want to access a particular person inside it, therefore I figured that using the ID number as the key would work
Thanks guys! :-)
Use a dictionary object
var people = {};
people[4] = 'me';
I'd suggest you use collections. A collection is an array of objects. You can then pass properties on each person. You can filter your collection by any property. So close to what you're doing, but instead of relaying on the index, pass the id for each person.
var people = []; // a collection
var person = {
id: 4,
name: 'John'
};
people.push(person);
// Filtering:
// By id
var john = people.filter(function(person) {
return person.id == 4;
});
// By name
var john = people.filter(function(person) {
return person.name == 'John';
});
You can abstract those loops above to re-use them. Also make sure your id's are unique. If data is coming from the DB it should be OK, otherwise I'd keep track of them somewhere.
The advantage of collections, as opposed to a plain object with keys is that you can sort and filter, while an object, where the order of properties is not guaranteed, you can't do it as simple.
Note that filter only works on "modern browsers", so IE9+, but there are polyfills for older browsers.
when we use a string as key, like this:
var people = {}; //this is an object
people[name] = 'toto';
we are adding new property to this object, because each object in javascript can be seen as a hashtable.
If you use an array, it's still an object, you can add properties to it using string as key. But if you do something like people[4] = 'toto';, you are adding a string to the array, the length of the array will then become 5. Of course the number 4 will still be a property of this array object.

Get/find javascript object by its parameter

Considering I have an array of objects, and all objects represent something out of a database, thus they have an unique identifier.
Now I also have the ID and the correct array. How do I search each object in that array where the parameter 'id' equals my ID. (The point is, I don't know the internal identifier for that object. All I have is an ID and I need the entire object for description, last_user, created etc..)
Object
created: "2011-06-08 15:47:11"
description: "Something new.."
id: "1"
last_user: "1"
P.s. I have jQuery embedded, so if there's no default way, a jQuery function would suffice.
$.grep() should do it. In the following example arr is your array of objects. It will find the element that has an id of 1.
var obj = jQuery.grep(arr, function(el, i){
return el.id == 1;
})[0];
You could loop through your array of objects, and check for each one if yourObject.id is equal to the id you are looking for. Then you'll be able to get the other fields, such as yourObject.created

Categories