Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  94] [ 2]  / answers: 1 / hits: 77670  / 13 Years ago, tue, february 7, 2012, 12:00:00
var arr = [{
key: key1, value: z
}, {
key: key2, value: u
}, {
...
}];


How to check whether my key:key1 exists already or not. If it does not exist, i need to add the key in ma array.



if(arr.hasOwnProperty(key1)){
arr.unshift({key:key1, value:z});
}

More From » javascript

 Answers
1

Since you've got an Array filled with Objects, you need to do it like:



(ES3)



function lookup( name ) {
for(var i = 0, len = arr.length; i < len; i++) {
if( arr[ i ].key === name )
return true;
}
return false;
}

if( !lookup( 'key1' ) ) {
arr.push({
key: 'key1',
value: 'z'
});
}

[#87610] Sunday, February 5, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raynamadilynl

Total Points: 653
Total Questions: 110
Total Answers: 98

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
raynamadilynl questions
;