1

I want to filter All taskLists data into open and closed tasklists using status key

var data = [{
  "createdOn": "Created on Jan 07, 2017",
  "taskList": [{
    "task": "Meeting with Jason",
    "status": "closed",
  },
  {
    "task": "Meeting with Ram",
    "status": "open",
  },
  ]
},
{
  "createdOn": "Created on Jan 08, 2017",
  "taskList": [{
    "task": "Meeting with Mike",
    "status": "open",
  },
  {
    "task": "Meeting with Smith",
    "status": "closed",
  },
  ]
}
];

I have tried with this:

console.log(_.filter(data, { taskList: [ { status: "open" } ]}));

Actual Result:

According to data, TaskList array contains 2 open status on Jan 07 and Jan 08. But I am getting an entire array of taskList.

0:{createdOn: "Created on Jan 07, 2017", taskList: Array(2)}
1:{createdOn: "Created on Jan 08, 2017", taskList: Array(2)}

Expected Result:

0:{createdOn: "Created on Jan 07, 2017", taskList: "taskList": [{
    "task": "Meeting with Ram",
    "status": "open",
  }} 
1:{createdOn: "Created on Jan 08, 2017", taskList: "taskList": [{
    "task": "Meeting with Mike",
    "status": "open",
  }}

2 Answers 2

1

Your filter is wrong.

var data = [{
  "createdOn": "Created on Jan 07, 2017",
  "taskList": [{
    "task": "Meeting with Jason",
    "status": "closed",
  },
  {
    "task": "Meeting with Ram",
    "status": "open",
  },
  ]
},
{
  "createdOn": "Created on Jan 08, 2017",
  "taskList": [{
    "task": "Meeting with Mike",
    "status": "open",
  },
  {
    "task": "Meeting with Smith",
    "status": "closed",
  },
  ]
}
];
var newArray = data.filter(function (el) {
  el.taskList = el.taskList.filter(function(item)
  {
		return item.status == "open";
  });
  return el;
});
console.log(newArray);

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

Comments

0

Your filter is fine if you want filter items that contains status='open'. If you want return modified object, its another story. This is ECMAS6 lodash/vanilla:

// lodash
console.log(_.map(data, o => o.taskList = _.filter(o.taskList, { 'status': 'open' })));

// vanilla
console.log(data.map(o => o.taskList = o.taskList.filter(t => t.status == 'open')))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script>
var data = [{
  "createdOn": "Created on Jan 07, 2017",
  "taskList": [{
    "task": "Meeting with Jason",
    "status": "closed",
  },
  {
    "task": "Meeting with Ram",
    "status": "open",
  },
  ]
},
{
  "createdOn": "Created on Jan 08, 2017",
  "taskList": [{
    "task": "Meeting with Mike",
    "status": "open",
  },
  {
    "task": "Meeting with Smith",
    "status": "closed",
  },
  ]
}
];
</script>

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.