1

I want to show a list of user uids and some information about them, except for the information of a specific user.

Here is an example of my JavaScript object, which I am storing in as a usersData state:

{
  "alkfklnj2340": {
    "uid": "alkfklnj2340",
    "username": "username1"
  },
  "235o2hifoiid": {
    "uid": "235o2hifoiid",
    "username": "username2"
  }
}  

For example, I want to return a new object without alkfklnj2340, so:

{
  "235o2hifoiid": {
    "uid": "235o2hifoiid",
    "username": "username2"
  }
}

I have tred this so far, which doesn't quite output what is expected:

const filteredUsers = Object.keys(this.state.usersData).filter((key, i) =>
    this.state.usersData[key].uid != this.state.userUid
);
1
  • What are you expecting it to output and what value are you getting? What is userUid? Commented Nov 29, 2019 at 4:30

2 Answers 2

1

You could use a for...in loop

let result = {};
for (const key in this.state.usersData) {
    if (key !== this.state.userUid) {
        result[key] = this.state.usersData[key];
    }
}

or a forEach loop:

let result = {};
Object.keys(this.state.usersData).forEach(key => {
  if (key !== this.state.userUid) {
    result[key] = this.state.usersData[key];
  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can use reduce to construct a new dictionary.

var filteredUsers = Object.keys(this.state.usersData).reduce((filteredUsers, key) => {
    if (this.state.usersData[key].uid != this.state.userUid) {
        filteredUsers[key] = this.state.usersData[key];
    }
    return filteredUsers;
}, {});

This will start from a new dictionary {} and keep setting key+value when the condition is met.

You can also do it like this:

var filteredUsers = Object.fromEntries(Object.entries(this.state.usersData).filter(([key,value]) => this.state.usersData[key].uid != this.state.userUid));

Object.entries() turns dictionary into an entry list. Object.fromEntries() turns an entry list back to a dictionary.

Comments

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.