首页 > 解决方案 > Using .map method to update the object that I'm evaluating

问题描述

I am executing the map method on an array selectedItem where selectedItem has a string property nodeType and an object property items :

items = { computers: 0, drives: 0, files: 0, folders: 0 }

selectedItem?.map(item => {
  switch (item.nodeType) {
    case 'FileType':
      return (items.files += 1);
    case 'FolderType':
      return (items.folders += 1);
    case 'DriveType':
      return (items.drives += 1);
    case 'ComputerType':
      return (items.computers += 1);
    default:
      return;
  }

I know I should be able to replace the switch statement by using the built-in functionality of the map method (hasOwnProperty), but I've only seen examples where Object literals are used to match on in order to return the string, like this:

const itemTypes = {
        file: 'file',
        folder: 'folder',
        drive: 'drive',
        computer: 'computer'
    }

However, upon a .map(expression) match I want to execute a simple incrementing logic to +=1 to a property within the object I'm evaluating.

I've looked at .filter() and .reduce() but of course don't apply since they return a different array. I'm sure it may have to deal with writing the correct function within the .map(expression) but not sure how to do that.

I've looked at these SO posts, but they either don't apply or don't get me all the way there. The second link is very close to what I'm looking for but not sure how to apply it to my code:

How would I do that using only map and not nesting a switch within the map function?

标签: javascript

解决方案


map() is used to create a new array. It is not useful when you want to update an object.

You should be using reduce to count up all the types

const selectedItem = [
 { nodeType: 'FolderType' },
 { nodeType: 'DriveType' },
 { nodeType: 'DriveType' },
 { nodeType: 'FolderType' },
 { nodeType: 'ComputerType' },
];
const types = {
  FileType: 'files',
  FolderType: 'folders',
  DriveType: 'drives',
  ComputerType: 'computers'
};

const items = {
  computers: 0,
  drives: 0,
  files: 0,
  folders: 0
};

selectedItem?.reduce((obj, item) => {
  const type = types[item.nodeType];
  if (type) obj[type]++;
  return obj;
}, items);

console.log(items);

or forEach

const selectedItem = [
 { nodeType: 'FolderType' },
 { nodeType: 'DriveType' },
 { nodeType: 'DriveType' },
 { nodeType: 'FolderType' },
 { nodeType: 'ComputerType' },
];
const types = {
  FileType: 'files',
  FolderType: 'folders',
  DriveType: 'drives',
  ComputerType: 'computers'
};

const items = {
  computers: 0,
  drives: 0,
  files: 0,
  folders: 0
};

selectedItem?.forEach((item) => {
  const type = types[item.nodeType];
  if (type) items[type]++;
});

console.log(items);


推荐阅读