Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

javascript - Helper function to retrieve a value from an object fails with more than one item in the object

I have a helper function to retrieve a user's name or email from the redux store when the user's UID is passed as an argument

From the store

console.log(typeof users) //object
console.log(users)

[
    0: {
        displayName: "User One"
        email: "[email protected]"
        id: "c9E5RfPVVxMNPz3MsORs76cG46G3"
    },
    1: {
        displayName: "User Two"
        email: "[email protected]"
        id: "mbuPoIcEMOhEvSB23IRqj5AIbZn2"
    }
]
// getUserDetails.js

import { useSelector } from 'react-redux';

export function getUserDetails(searchKey) {
  const users = useSelector((state) => state.firestore.ordered.users);
  console.log(users)
  console.log(typeof users)
  return (
    users &&
    searchKey &&
    users.filter(function (obj) {
      return Object.keys(obj).some(function (key) {
        return obj[key].includes(searchKey);
      });
    })
  );
}

And it is used by my @devexpress/dx-react-grid CRUD tables, by taking the field createdBy: fdsj75g43hfihsdhi and returning a name or email, like this:

  const UserNameFormatter = ({ value }) => {
    return getUserDetails(value)[0].displayName;
  };

The function works great with only one user, but as soon as I add another user to Firestore, the function throws an error:

TypeError: obj[key].includes is not a function
(anonymous function)
src/utils/getUserDetails.js:10
   7 |   searchKey &&
   8 |   users.filter(function (obj) {
   9 |     return Object.keys(obj).some(function (key) {
> 10 |       return obj[key].includes(searchKey);
     | ^  11 |     });
  12 |   })
  13 | );

I appreciate any suggestions, thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It seems that you're expecting each key to be a string, but that's not always the case.

I recommend doing a check before using the includes method like this:

import { useSelector } from 'react-redux';

export function getUserDetails(searchKey) {
  const users = useSelector((state) => state.firestore.ordered.users);
  console.log(users)
  console.log(typeof users)
  return (
    users &&
    searchKey &&
    users.filter(function (obj) {
      return Object.keys(obj).some(function (key) {
        return typeof obj[key] === "string" && obj[key].includes(searchKey);
      });
    })
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...