I want it to ignore the element with the initial "recebeu" and only send what starts with "user", how can I do that?...
const array = [
{
member: "Joao",
user: {
user: "id1",
user2: "id2",
user3: "null",
recebeuuser: "null"
},
},
{
member: "Pedro",
user: {
user: "id1",
user2: "id2",
user3: "null",
recebeuuser: "name"
},
},
];
const filteredUsers = (user) => Object.values(user).filter(u =>
u !== 'null' && typeof u === 'string'
)
const mentionUser = (user) => `<@${user}>`
const stringify = (m) => `${m.member} - ${filteredUsers(m.user).map(mentionUser).join(', ')}`
console.log(array.map(stringify).join('\n'))
Joao - <@id1>, <@id2>
Pedro - <@id1>, <@id2>, <@name>
I think part of the problem is that you're using a lot of shortcuts without fully understanding the shape of what you're passing around. I would recommend simplifying the code and avoiding shorthand notation.
Here is a refactored version of what you are doing using a simple for...of loop iterating over the Object.entries() of the user property of each passed object. If the key and value pass all the conditions a formatted string is pushed to the users array. Finally it returns the fully formatted string.
function stringifyMember(memberObject) {
const { member, user } = memberObject;
const users = [];
for (const [k, u] of Object.entries(user)) {
if (k.startsWith('user') && u !== 'null' && typeof u === 'string') {
users.push(`<@${u}>`)
}
}
return `${member} - ${users.join(', ')}`
}
const array = [{ member: "Joao", user: { user: "id1", user2: "id2", user3: "null", recebeuuser: "null" }, }, { member: "Pedro", user: { user: "id1", user2: "id2", user3: "null", recebeuuser: "name" }, },];
console.log(array.map(m => stringifyMember(m)).join('\n'))
also see: