2

Let's say I have a data and a map.

let data = [
    { 
        'name': 'bob',
        'items': ['111']
    },
    { 
        'name': 'Jane',
        'items': ['111']
    },
    { 
        'name': 'Greg',
        'items': ['222']
    }
]

let item_map = [
    { 'Item1': '111', 'Item2': '222'}
]

The items in data object contains the ids of the item. What I am trying to do is to filter out the object from data where using a list of values matched to the id of the map.

For example, given ['Item1'], I want to get

[{ 
        'name': 'bob',
        'items': ['111']
    },
    { 
        'name': 'Jane',
        'items': ['111']
}]

What I tried is

data.filter( item => ['111'].some(filter => (item_map["Item1"]).includes(filter)))

But this keeps giving me a Uncaught TypeError: Cannot read property 'includes' of undefined error.

EDIT

data.filter(item => ['111'].some(filter => item_map[0]["Item1"].includes(filter)))

This is what I newly tried, but this just returns all three items.

5
  • item_map does not have an "Item1" property. It is an array, and its element is an object with that property. Commented Sep 12, 2019 at 19:39
  • Yes, I fixed that and I am still getting a wrong output. It gives me something though. Any help? Commented Sep 12, 2019 at 19:40
  • Maybe remove that first attempt from your question, since it is ... no longer your question. Commented Sep 12, 2019 at 19:41
  • Wait so is the item_map what you want your output to look like? Commented Sep 12, 2019 at 19:41
  • What you did does not make sense: you take a literal array with one literal string "111", and then check that "Item1" (which is "111") includes "111". This is obviously true, no matter how many times you iterate over data. You don't actually use the item you get from data. Commented Sep 12, 2019 at 19:43

1 Answer 1

3

I can't exactly understand why you'd choose an array for an items "map", but to conform with your current data structure, this is the correct logic:

let filters = ['Item1'];
data.filter((datum) => {
    return filters.some((filter) => datum.items.includes(item_map[0][filter]));
});
Sign up to request clarification or add additional context in comments.

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.