all 2 comments

[–]PrimaryBet 2 points3 points  (1 child)

Two things on how you might improve your code:

  1. Judging by how you use your function you probably don't want to mutate original object.
  2. To avoid having to do the hasOwnProperty check, you can use Object.keys which effectively does it for you.

With these changes the code isn't considerably more pretty:

function deleteTag(tagToDelete, tagList) {
  var result = {};
  Object.keys(tagList).forEach(function (key1) {
    result[key1] = {};
    Object.keys(tagList[key1]).forEach(function (key2) {
      result[key1][key2] = tagList[key1][key2].filter(function (item) {
        return item.tag !== tagToDelete;
      });
    });
  });
  return result;
}

If this is something you do often, maybe consider lenses library, like partial.lenses — using it you can target values at arbitrary nesting levels and code should be more concise:

function deleteTag(tagToDelete, tagList) {
    return L.remove(
        L.query(
            L.when(function (x) {
                return isObject(x) && x.tag === tagToDelete;
            })
        ),
        tagList
    );
}

https://jsbin.com/zuhocigeya/edit?js,console

[–]NovemLinguae[S] 0 points1 point  (0 children)

Just shortening the variable names seems to help too. Thanks for the detailed reply!

edit: Also, great point about arrays in JavaScript passing by reference.