json object key is getting added even if array has the key

时间:2015-11-25 10:23:01

标签: javascript json

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);
}

JSFIDDLE

的颜色

1 个答案:

答案 0 :(得分:2)

_jsonArray 是对象数组。如果属性已存在,则必须检查每个对象。

试试这段代码。

&#13;
&#13;
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);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

希望这会对你有所帮助。