0

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

2
  • 2
    sigh. It sounds like you need a "map" (or object) rather than an "array", but without knowing how the data is supposed to be used we can't tell. If this is the case then the previous question you asked about variable key names is probably moot. Commented Nov 25, 2015 at 10:25
  • i.e. it's likely that you're not using the right data structure in the first place Commented Nov 25, 2015 at 10:30

1 Answer 1

2

_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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it worked,btw I am also using web worker so I replace $.map with Array.prototype,map.call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.