I\'m trying to take some data from an existing object and group it into a new one. The problem I am having is checking if the object key exists so I can either create a new
You can use hasOwnProperty() function.
var groups = [];
for (var i=0; i<something.length; i++) {
var group_key = 'group_'+something[i].group_id;
if (!groups.hasOwnProperty(group_key)) {
// New group
var group_details = {};
group_details[group_key] = {//maybe change to group_details =
group_name: something[i].group_name,
items: [
{ 'name': something[i].name }
]
};
//groups.push(group_details);
//change it to
groups[group_key] = group_details;
} else {
// Existing group
groups[group_key].items.push({
'name': something[i].name
});
}
}
The best way to achieve this would be to rely on the fact that the in
operator returns a boolean value that indicates if the key is present in the object.
var o = {k: 0};
console.log('k' in o); //true
But this isin't your only issue, you do not have any lookup object that allows you to check if the key is already present or not. Instead of using an array, use a plain object.
var groups = {};
Then instead of groups.push(...)
, do groups[group_key] = group_details;
Then you can check if the group exist by doing if (group_key in groups) {}
let data = {key: 'John'};
console.log( data.hasOwnProperty('key') );
you could retrieve keys from object and iterate through the list and see if the key is exist or not:
var keys=Object.keys(object)
for(var i=0;i<keys.length;i++){
if(keys[i]=="your key"){//check your key here}
}
You should use the in
operator
key in object //true
!(key in object) //false
And undefined
can not be used
obj["key"] !== undefined //false, but the key in the object
For more information, please look at Checking if a key exists in a JavaScript object?
ExampleArray
[0] => siteoverlay
[1] => overlaycenter
[2] => someelementid
extend prototype if you want,(function here with while loop which is much faster than for in):
if (!('getKey' in Object.prototype)) {
Object.prototype.getKey = function(obj) {
var i=this.length;
while(i--)
{ if(this[i]===obj)
{return i;}
return;
}
};
}
then you can use:
alert(exampleArray.getKey("overlaycenter"));
returns: 1
also with prototype extension:
if(!('array_flip' in Array.prototype)){
Array.prototype.array_flip=function(array) {
tmp_ar={}; var i = this.length;
while(i--)
{ if ( this.hasOwnProperty( i ) )
{ tmp_ar[this[i]]=i; }
} return tmp_ar;
};
}
and then you can use:
alert(exampleArray.array_flip(exampleArray['someelementid']);
returns: 2
found out without prototype addition it is also functional
and eventually better for compatible scripting as everyone says not to extend the prototype...and so,...yes, if you want to use it with an easy 1 liner then you can use:
function array_flip( array )
{ tmp_ar={}; var i = array.length;
while(i--)
{ if ( array.hasOwnProperty( i ) )
{ tmp_ar[array[i]]=i; }
} return tmp_ar;
}
And
alert(array_flip(exampleArray)['siteoverlay']);
returns 0