0

I need to create a pipe that filters out an array of objects based on whether the indexof methods shows that the various strings within the object are similar.

So for example if we have the array

[{name: "john",
age: "17"},
{ name: "rob",
age: "20"}
]

and I have the filter object

{name: "jo",
age: "1" }

it will return the object {name: "john", age: "17"}.

Note: The numbers are purposefully made as strings.

How would I go about making a pipe that does this?

1
  • Don't abuse pipes. Pipes are designed primarily for last-mile format conversions related to how something is displayed, not for business logic, filtering, or sorting. Implement filtering and sorting in the component TS logic. Commented Aug 10, 2017 at 18:51

2 Answers 2

1

I don't know angular this is how you can do in JavaScript, I hope it helps

var data = [{name: "john",
age: "17"},
{ name: "rob",
age: "20"}
];

var filter = {name: "jo", age: "1" };

var filtered = data.filter(function (person) {
    // check objects keys are the same
    if (Object.keys(person).join("") !== Object.keys(filter).join("")) return false;

    //compare values
    for (var key in filter) {
        //false if empty string
        if (filter[key] === "") return false; 
        if(person[key].indexOf(filter[key])) {
            return false;
        }
    }
    return true;
});
console.log(filtered);
Sign up to request clarification or add additional context in comments.

6 Comments

I'm going to follow the advice in the comment. What you wrote here will help me a lot.
Just a question. Would this still work if one of the variables was missing from the filter object? Like say it was just {name: 'jo'} without the age variable?
you are right I added extra validation 1: keys need to be the same 2: empty filter will fail; it is better solution if you validate filer before that
So the objects have to be exactly the same? Also, what happens if I were to send an object that has all the variables but all the variables are empty?
Like var filter = {name:"", age:""}. Would it return all the objects in the array?
|
0

It is a good and real use case in favor of using an Angular Pipe. Yes, you can bind for-loop with an array filtered beforehand, and moreover, it might be the preferable way in some circumstances. But anyway your situation is a good and appropriate chance to try Pipe.

Here is an example. Enjoy!

https://stackblitz.com/edit/angular-with-filter-pipe-example

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.