Home > Enterprise >  Skip over element in .map without adding .filter etc
Skip over element in .map without adding .filter etc

Time:07-15

I'm looking for beautiful solution I have array items. Item consists of user_id and some other information. I need map all items and for each item find user with appropriate id. Then add to item some information from user

items = items.map((item) => {
                let user = users.find(u => item.user_id === u.id);

                item.email = user.email;
                item.user_name = user.name;
                return item;
            });

But if user with item.user_id doesn't exist I must do nothing. I already have iterations of two arrays and don't want add more

CodePudding user response:

It depends what you mean by "skip over element."

If you mean "don't include it in the output array," then you'll have to put map aside, because map will always produce an output element for an input element. Instead, you can just loop through pushing to a new array:

const originalItems = items;
items = [];
for (const item of originalItems) {
    let user = users.find(u => item.user_id === u.id);
    if (user) {
        item.email = user.email;
        item.user_name = user.name;
        items.push(item);
    }
}

If you just mean "don't add the user information" (but do keep items you don't add information to), then you can just branch:

items = items.map((item) => {
    let user = users.find(u => item.user_id === u.id);
    if (user) {
        item.email = user.email;
        item.user_name = user.name;
    }
    return item;
});

That raises the question of why you're using map at all, though, since there doesn't immediately seem to be much reason to create a new array with the same objects in it (even if we're adding to those objects). If you're using something like React where state updates must not modify existing objects, you'd want to create a new item for any item you changed instead:

items = items.map((item) => {
    let user = users.find(u => item.user_id === u.id);
    if (user) {
        item = {
            ...item,
            email: user.email,
            user_name = user.name,
        };
    }
    return item;
});

But you may not be doing that, you haven't said.

CodePudding user response:

Maybe try:

array.map(x => condition ? parse(x) : x);

smth. like that

  • Related