2

I have an array of object, that contain key value pair of columnNames.

when i check if a particular columnName exists it alwayz returns -1

Here is an sample http://jsfiddle.net/trLkt/6/, Help will b appriciated

2 Answers 2

3

You're searching for string values in the columnModel array, but you're storing objects in it (columnModel.push({'colName': $(this).text()});). $.inArray() cannot decide by itself to compare against the colName property of each array element, it simply compares the value you're searching for against each array element.

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

2 Comments

then how should i check if an object exists in that array or not
You need to add plain strings to that array (columnModel.push($(this).text())), or you cannot use $.inArray(). If you really need to store objects in the array, you will need to iterate over the array yourself and compare each element's colName property.
2

Two things you can do:

Add strings to the array instead of objects using .push (as suggested by @lanzz), then $.inArray will work as you expect.

Alternatively, if you do need to store objects within the array (if for example you need to have multiple properties within each object) you would need to iterate over each object and see if the colName already exists:

    var colExists = false;
    var text = $(this).text();
    $.each(columnModel, function(k, v) {
      if(text == v['colName']) {
        colExists = true;
      }
    });

Then change your check from if(colExists === -1) to if(!colExists).

Example

$(function () {
  $('#ddlMain').change(function (event) {
    $('option:selected', $(this)).each(function () {

      var colExists = false;
      var text = $(this).text();

      $.each(columnModel, function(k, v) {
        if(text == v['colName']) {
          colExists = true;
        }
      });

      if(!colExists) {
        columnModel.push({'colName': $(this).text()});
        alert($(this).text() + ' added to columnModel');
      }

    });
  });
});

1 Comment

Thanks, I think this is the best that can be done. I am actually using this array with jQuery template plugin to generate a dynamic table header. Template plugin uses an array of objects so needed an array of objects

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.