0

I'm trying to remove an item from a nested object. object named "categories" that contains several categories and each category has several businesses. something like bellow object:

let categories = [{
  name: 'Home',
  biz: [{
    name: 'Business 1',
    id: 50
  }, {
    name: 'Business 2',
    id: 52
  }, {
    name: 'Business n',
    id: 53
  }]
}, {
  name: 'Car',
  biz: [{
    name: 'Business 1',
    id: 62
  }, {
    name: 'Business 2',
    id: 66
  }, {
    name: 'Business n',
    id: 67
  }]
}];

What I'm trying to do is removing one of this businesses that selected by user and return the whole object without mutating original state.

so far I did something like bellow and it's working fine bu I'm not sure if I'm doing this the right way or the wrong way. I appreciate if you guys help me by review or refactor this code:

categories.map((cat, inedx) => {
  return { ...cat, biz: [...cat.biz.filter(bz => bz.id!== 66)]}
});
1
  • No need for the [...array] otherwise its fine. Commented Jan 6, 2019 at 13:42

2 Answers 2

1

reduce to the rescue :-)

const fn = (categories, id) => {
  return categories.reduce((r, x) => {
    return r.concat({ ...x, biz: x.biz.filter(x => x.id !== id) });
  }, []);
}

console.log(fn(categories, 66));
Sign up to request clarification or add additional context in comments.

3 Comments

EDIT: this is minimal example, you also would like to add some type checks (e.g. is x.biz array? etc).
I always get confused when I want to use this method :-)
been there :-) when you do a lot of practices, it will sit in your mind, no worries.
0

    let categories = [{
        name: 'Home',
        biz: [{
            name: 'Business 1',
            id: 50
        }, {
            name: 'Business 2',
            id: 52
        }, {
            name: 'Business n',
            id: 53
        }]
    }, {
        name: 'Car',
        biz: [{
            name: 'Business 1',
            id: 62
        }, {
            name: 'Business 2',
            id: 66
        }, {
            name: 'Business n',
            id: 67
        }]
    }];

categories.forEach(el => el.biz = el.biz.filter(e => e.id !== 66));

    console.log("removed  biz 66", categories)

2 Comments

This solution is returning a whole new object every time. When the request was “without mutating the original” object
without return "whole new object"

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.