0

I am trying to filter javascript object using filter function .But I am getting error key is not defined .here is my code https://jsfiddle.net/13n8n3om/

var arr=[
  {
    "EX": {

      "division": "abc",
      "is_active": true,

    }
  },
 {
    "PY": {

      "division": "pqwww",
      "is_active": false,

    }
  }
];

 arr = arr.filter(function(obj) {
                return obj[key] !== 'EX';
            });

            console.log(arr)

Expected output

[

 {
    "PY": {

      "division": "pqwww",
      "is_active": false,

    }
  }
]
4
  • Well thats because you never define key Commented Mar 28, 2016 at 9:37
  • 1
    obj[Object.keys(obj)[0]] would probably work. Commented Mar 28, 2016 at 9:38
  • 1
    obj.hasOwnProperty('EX') should work. @Andy it may not work if obj has more than one properties. Commented Mar 28, 2016 at 9:43
  • Yeah, that's preferable. I always forget about that method. Commented Mar 28, 2016 at 9:45

3 Answers 3

1

Just check the key of the object if it is unequal with the given string.

var arr = [{ "EX": { "division": "abc", "is_active": true, } }, { "PY": { "division": "pqwww", "is_active": false, } }];

arr = arr.filter(function (obj) {
    return Object.keys(obj)[0] !== 'EX';
});

document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');

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

Comments

1

replace

return obj[key] !== 'EX';

with

return Object.keys(obj)[0] !== 'EX';

basically you need to access the first property of obj and key is undefined.

1 Comment

@user944513 correct it again... Nina's answer should work for you.
0

You need to check that the obj isn't EX like so :

arr = arr.filter(function(obj, key) {
          if (! obj.EX) {
              return obj;
          }
       });

Comments

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.