2

I've hit a snag after a few hours -- wondered if a fresh minded developer can just review the below, the code is simplied to show the problem.

I am filtering a property value on an array of objects, and cross referencing that property with an array which has matching keys, and boolean values to control if it should be factored into the filter.

However my result is returning all 3 objects, despite the console.log seeming to evaluate correctly. Any ideas?

Many thanks...

var data = [{
    "id": 1,
    "status": "new",
  },
  {
    "id": 2,
    "status": "rejected",
  },
  {
    "id": 3,
    "status": "changed",
  }
];

var filter = {
  "new": true,
  "rejected": false,
  "changed": true
}

var result = data.filter(function(item) {
  var arr = [];

  Object.keys(filter).forEach(function(key) {
    if (item.status === key && filter[key] === true) {

      console.log('---')
      console.log('item.status', item.status)
      console.log('key', key)
      console.log('filter[key]', filter[key])
      console.log('---')

      arr.push(item);
    }
  });

  return arr;
});
0

3 Answers 3

3

You're making this a bit more complicated than you need to. The function passed to filter() should return a boolean — you're returning an array.

You can simply filter with the lookup on the filter array, which will either return false or undefined, in which case you filter it out, or true, in which case you keep it..

var data = [{
    "id": 1,
    "status": "new",
  },
  {
    "id": 2,
    "status": "rejected",
  },
  {
    "id": 3,
    "status": "changed",
  }
];

var filter = {
  "new": true,
  "rejected": false,
  "changed": true
}

var result = data.filter(item => filter[item.status])

console.log(result)

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

Comments

2

You filter by returning something truthy or falsey directly, not by returning anything more specific (like an object). You can simplify your code to a one-liner:

var data=[{"id":1,"status":"new",},{"id":2,"status":"rejected",},{"id":3,"status":"changed",}]
var filter = {
  "new": true,
  "rejected": false,
  "changed": true
}

var result = data.filter((item) => filter[item.status])
console.log(result);

Comments

2

filter will create a new array with every item that returned a truthy value. This should work:

var result = data.filter(function(item) {
  return filter[item.status];
});

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.