即使数组具有键,也会添加json对象键

时间:2021-07-20 21:14:34

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?

我循环遍历一个数组并检查第二个数组是否有一个该名称的密钥。如果没有,则将此当前名称添加为第二个数组的键。我检查了hasOwnProperty并且也检查了但是在这两种情况下,密钥都被添加到第二个数组中,尽管该名称的密钥已经存在。如果密钥已经存在,是否可以停止添加密钥?

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

的jsfiddle

1 个解决方案

#1


2  

_jsonArray is array of object. You must check each objects, if the property is already there.

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

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.

希望这会帮助你。

#1


2  

_jsonArray is array of object. You must check each objects, if the property is already there.

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

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.

希望这会帮助你。