Reputation: 50326
I am looping through an array and checking if a second array has a key by that name. If not then add this current name as a key to second array. I check with hasOwnProperty
and also with in
but in both cases the key is getting added in second array though a key by that name is already present.How can stop a key getting added if it is already present?
function(){
var _arraySource = ['Tea', 'Coffe', 'Banana', 'Orange', 'Tea'];
var _jsonArray = [];
for(var i = 0, j = _arraySource.length; i<j; i++){
if(_jsonArray.hasOwnProperty(_arraySource[i])){
//Do nothing
}
else{
var _key =_arraySource[i];
var myObj = {};
myObj[_key] = "";
_jsonArray.push(myObj);
}
}
console.log(_jsonArray);
}
Upvotes: 0
Views: 43
Reputation: 825
_jsonArray is array of object. You must check each objects, if the property is already there.
Try this code.
var _arraySource = ['Tea', 'Coffe', 'Banana', 'Orange', 'Tea'];
var _jsonArray = [];
for (var i = 0, j = _arraySource.length; i < j; i++) {
var obj = $.map(_jsonArray, function (data) {
if (data.hasOwnProperty(_arraySource[i]))
return data;
});
if (obj.length) {
console.log(_arraySource[i]);
}
else {
var _key = _arraySource[i];
var myObj = {};
myObj[_key] = "";
_jsonArray.push(myObj);
}
}
console.log(_jsonArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this will help you.
Upvotes: 2