I have the next object:
var persons= {};
persons["Matt"].push("A");
persons["Matt"].push("B");
persons["Matt"].push("C");
And I want to know if the object contains the element which I try to insert.
E.g:
persons["Matt"].push("A"); /* The element A already exist... And I don't want duplicate elements.*/
Anybody know one way to make it?
EDIT WITH MORE DETAILS:
I have a the next code:
function insertIfNotThere(array, item) {
if (array.indexOf(item) === -1) {
array.push(item);
}
}
function EventManager(target) {
var target = target || window, events = {};
this.observe = function(eventName, cb) {
if (events[eventName]){
insertIfNotThere(events[eventName], cb);
}else{
events[eventName] = []; events[eventName].push(cb);
}
return target;
};
this.fire = function(eventName) {
if (!events[eventName]) return false;
for (var i = 0; i < events[eventName].length; i++) {
events[eventName][i].apply(target, Array.prototype.slice.call(arguments, 1));
}
};
}
I use your method for checking if the element with the content indicated exist. But... It push the element ever... I don't know what's happening...
First things first. When you do
persons= {};
you are creating a global property called persons and assigning an empty object to it. You might want a local variable here. So, change it to
var persons = {};
And then, when you create a new key in the object, by default, the value will be undefined. In your case you need to store an array. So, you have to initialize it like this
persons['Matt'] = [];
and then you can use the Array.prototype.indexOf function to find out if the item being added is already there in the array or not (it returns -1 if the item is not found in the array), like this
if (persons['Matt'].indexOf("A") === -1) {
persons['Matt'].push("A");
}
if (persons['Matt'].indexOf("B") === -1) {
persons['Matt'].push("B");
}
You can create a function to do this
function insertIfNotThere(array, item) {
if (array.indexOf(item) === -1) {
array.push(item);
}
}
var persons = {};
persons['Matt'] = [];
insertIfNotThere(persons['Matt'], 'A');
insertIfNotThere(persons['Matt'], 'B');
// This will be ignored, as `A` is already there in the array
insertIfNotThere(persons['Matt'], 'A');
Use indexOf to check for the existence of A. If it doesn't exist (is -1), add it to the array:
if (persons['Matt'].indexOf('A') === -1) {
persons['Matt'].push('A');
}
Related
I use the following code, in a nodejs app, to build a tree from an array of database rows that form an adjacency list:
// Lay out every node in the tree in one flat array.
var flatTree = [];
_.each(rows, function(row) {
flatTree.push(row);
});
// For each node, find its parent and add it to that parent's children.
_.each(rows, function(row) {
// var parent = _.find(flatTree, function(p) {
// p.Id == row.ParentId;
// });
var parent;
for (var i = 0; i < flatTree.length; i++){
if (flatTree[i].Id == row.ParentId) {
parent = flatTree[i];
break;
}
};
if (parent){
if (!parent.subItems) {
parent.subItems = [];
};
parent.subItems.push(row);
}
});
I expect the commented out _.find call to do exactly the same as what the work-around for loop below it does, but _.find never finds the parent node in flatTree, while the for loop always does.
Similarly, a call to _.filter just doesn't work either, while the substitute loop does:
// var rootItems = _.filter(flatTree, function (node) {
// //node.ParentId === null;
// node.NoParent === 1;
// })
var rootItems = [];
for (var i = 0; i < flatTree.length; i++){
if (flatTree[i].ParentId == null){
rootItems.push(flatTree[i]);
}
}
I am using the underscore-node package, but have tried and had the same results with the regular underscore package.
Just missed the return.
var parent = _.find(flatTree, function(p) {
return p.Id == row.ParentId; // Return true if the ID matches
^^^^^^ <-- This
});
In your code nothing is returned, so by default undefined will be returned and parent will not contain any data.
Is it possible to create an array that will only allow objects of a certain to be stored in it? Is there a method that adds an element to the array I can override?
Yes you can, just override the push array of the array (let's say all you want to store are numbers than do the following:
var myArr = [];
myArr.push = function(){
for(var arg of arguments) {
if(arg.constructor == Number) Array.prototype.push.call(this, arg);
}
}
Simply change Number to whatever constructor you want to match. Also I would probably add and else statement or something, to throw an error if that's what you want.
UPDATE:
Using Object.observe (currently only available in chrome):
var myArr = [];
Array.observe(myArr, function(changes) {
for(var change of changes) {
if(change.type == "update") {
if(myArr[change.name].constructor !== Number) myArr.splice(change.name, 1);
} else if(change.type == 'splice') {
if(change.addedCount > 0) {
if(myArr[change.index].constructor !== Number) myArr.splice(change.index, 1);
}
}
}
});
Now in ES6 there are proxies which you should be able to do the following:
var myArr = new Proxy([], {
set(obj, prop, value) {
if(value.constructor !== Number) {
obj.splice(prop, 1);
}
//I belive thats it, there's probably more to it, yet because I don't use firefox or IE Technical preview I can't really tell you.
}
});
Not directly. But you can hide the array in a closure and only provide your custom API to access it:
var myArray = (function() {
var array = [];
return {
set: function(index, value) {
/* Check if value is allowed */
array[index] = value;
},
get: function(index) {
return array[index];
}
};
})();
Use it like
myArray.set(123, 'abc');
myArray.get(123); // 'abc' (assuming it was allowed)
I have an array of lightweight objects, each of which is the Subject of an Observer pattern. To conserve memory, when the Subject is no longer observed, i want to release the object's resources and make it remove itself from the parent array. So how do I ask either the parent object or the Array itself to splice the item, from code within the item itself? What I came up with is something like:
var parentObj = {
items : [],
addItem : function () {
var newItem = new ItemObj;
items.push(newItem);
},
removeItem : function (item) {
for (var i = this.items.length; i--; i < 0) {
if (this.items[i] == item) {
this.items.splice(i, 1);
return;
}
}
}
};
function ItemObj() {}
ItemObj.prototype = {
observers : [],
observerRemove : function(observer){
//find observer in observers array and splice it out
....
//now here's the part where it gets tricky
if (this.observers.length == 0) {
parentObj.removeItem(this);
}
},
//observerAdd.... etc
};
Which works, but only because parentObj is a named variable, if it were a class, it would not be so easy. Also, this seems a little clumsy. It would be nice if ItemObj could have some reference to it's parent Array object, but I can't find that. Any suggestions? Perhaps passing a reference from parentObj of itself to each ItemObj? as in
newItem.parentArray = this.items;
when creating the itemObj? Again, seems clumsy.
Why not just add a reference to the parent in the item class.
var parentObj = {
items : [],
addItem : function () {
var newItem = new ItemObj;
newItem.parent = this; // set the parent here
items.push(newItem);
},
removeItem : function (item) {
for (var i = this.items.length; i--; i < 0) {
if (this.items[i] == item) {
this.items.splice(i, 1);
return;
}
}
}
};
function ItemObj() {}
ItemObj.prototype = {
parent: null,
observers : [],
observerRemove : function(observer){
//find observer in observers array and splice it out
....
//now here's the part where it gets tricky
if (this.observers.length == 0) {
this.parent.removeItem(this); // use the parent here
}
},
//observerAdd.... etc
};
I am trying to recursively build an object with a tree of properties based on a MongoDB-ish selector "top.middle.bottom". There are some underscorejs helpers as well:
function setNestedPropertyValue(obj, fields, val) {
if (fields.indexOf(".") === -1) {
// On last property, set the value
obj[fields] = val;
return obj; // Recurse back up
} else {
var oneLevelLess = _.first(fields.split("."));
var remainingLevels = _.rest(fields.split(".")).join(".");
// There are more property levels remaining, set a sub with a recursive call
obj[oneLevelLess] = setNestedPropertyValue( {}, remainingLevels, val);
}
}
setNestedPropertyValue({}, "grandpaprop.papaprop.babyprop", 1);
Desired:
{
grandpaprop: {
papaprop: {
babyprop: 1
}
}
}
Outcome:
undefined
Helps and hints would be appreciated.
Instead of recursion I would choose for an iterative solution:
function setNestedPropertyValue(obj, fields, val)
{
fields = fields.split('.');
var cur = obj,
last = fields.pop();
fields.forEach(function(field) {
cur[field] = {};
cur = cur[field];
});
cur[last] = val;
return obj;
}
setNestedPropertyValue({}, "grandpaprop.papaprop.babyprop", 1);
EDIT
And here is another version thanks to the suggestions by Scott Sauyet:
function setPath(obj, [first, ...rest], val) {
if (rest.length == 0) {
return {...obj, [first]: val}
}
let nestedObj = obj[first] || {};
return {...obj, [first]: setPath(nestedObj, rest, val)};
}
function setNestedPropertyValue(obj, field, val) {
return setPath(obj, field.split('.'), val);
}
// example
let test_obj = {};
test_obj = setNestedPropertyValue(test_obj, "foo.bar.baz", 1);
test_obj = setNestedPropertyValue(test_obj, "foo.bar.baz1", 1);
// will output {"foo":{"bar":{"baz":1,"baz1":1}}}, while in the original version only "baz1" will be set
console.log(JSON.stringify(test_obj));
It's plain javascript
It only appends properties and will not override a top level object
setNestedPropertyValue() does not mutate the passed object (although keep in mind it only returns a shallow copy of the object, so some properties may be shared references between the original object and the new one)
I know this is old, but I needed exactly that kind of function and wasn't happy with the implementation, so here is my version:
function setNestedPropertyValue(obj, field, val) {
if (field.indexOf(".") === -1) {
obj[field] = val;
} else {
let fields = field.split(".");
let topLevelField = fields.shift();
let remainingFields = fields.join(".");
if (obj[topLevelField] == null) {
obj[topLevelField] = {};
}
setNestedPropertyValue(obj[topLevelField], remainingFields, val);
}
}
// example
let test_obj = {};
setNestedPropertyValue(test_obj, "foo.bar.baz", 1);
setNestedPropertyValue(test_obj, "foo.bar.baz1", 1);
// will output {"foo":{"bar":{"baz":1,"baz1":1}}}, while in the original version only "baz1" will be set
console.log(JSON.stringify(test_obj));
It's plain javascript
It only appends properties and will not override a top level object
setNestedPropertyValue() does not return the object so it is clear that it mutates the passed object
As mentioned by Jack in the question, I was not returning my object in the last line in the else statement. By adding this, it is now working:
obj[oneLevelLess] = setNestedPropertyValue( {}, remainingLevels, val);
return obj; // Add this line
}
I was wondering if it was possible to assign values to an element object. In this case, I wish to assign the returns from the setTimeout() function to an object within an element object.
For example:
var elem = document.getElementById('target');
elem.timeouts = new Object();
elem.timeouts.sometimeout = setTimeout('...', 1000);
So I could then do:
clearTimeout(elem.timeouts.sometimeout);
I know this might seem bad practice etc, but is it possible or will it cause browsers to catch fire and turn on their user etc.
Thanks.
DOM elements are Host objects (aka non-native) and as such they can do almost anything they want. It's not guaranteed that your expandos will work. In particular IE used to have problems with them. It's highly recommended to read this article:
What’s wrong with extending the DOM by #kangax
(it is from one of the Prototype.js developers who experienced the drawbacks of such bad habits. They've rewritten the whole library just to save themselfs from more headaches)
Now if you add uniqueID to elements in non-IE browsers (IE has it by default) and then your data function becomes a simple lookup ~ O(1). The real information will be stored in a closure.
It's 2-4x faster than jQuery.data (test)
data(elem, "key", "value");
1.) Hash table
var data = (function () {
var storage = {};
var counter = 1;
return function (el, key, value) {
var uid = el.uniqueID || (el.uniqueID = counter++);
if (typeof value != "undefined") {
storage[uid] || (storage[uid] = {});
storage[uid][key] = value; // set
} else if (storage[uid]) {
return storage[uid][key]; // get
}
};
})();
2.) Array
If you want to avoid expandos all together you can use an array to hold elements (but it's slower)
var data = (function () {
var elements = [];
var storage = [];
return function (el, key, value) {
var i = elements.indexOf(el);
if (typeof value != "undefined") {
if (i == -1) {
i = elements.length;
elements[i] = el;
storage[i] = {};
}
storage[i][key] = value; // set
} else if (storage[i]) {
return storage[i][key]; // get
}
};
})();
Array.prototype.indexOf (fallback)
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (item) {
var len = this.length >>> 0;
for (var i = 0; i < len; i++) {
if (this[i] === item) {
return i;
}
}
return -1;
};
}
You're welcome! :)
It's possible, DOM elements retrieved by JS, are JS variables :) ..BTW it's not a common practice do that stuff in that way. I think the answer of #galambalazs is more deep and complete ;)
if you are using jquery, you can story it in the "data"
http://api.jquery.com/jQuery.data/
No, actually that should work just fine. From what I understand, adding that return to the object should be fine. It's better than storing it in a global container IMO.