Check if userid matches one in the array - javascript

I'm attempting to check if a user's ID is in this array and if they are, also get the "text" from it.
Array:
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
I've tried if (staff.user.includes(msg.member.id)) (Which I didn't think was going to work, and didn't.)

const findUser = (users, id) => users.find(user => user.id === id)
const usersExample = [
{
id: '123456765',
text: 'sdfsdfsdsd'
},
{
id: '654345676',
text: 'fdgdgdg'
}
]
//////////////////
const user = findUser(usersExample, '123456765')
console.log(user && user.text)

The some method on an array is used to tell if an item meets a condition, it is similar to the find method but the find method returns the item where the some method return true or false.
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
const isStaff = (staff, id) => staff.some(s => s.user === id);
console.log(isStaff(staff, '123'));
console.log(isStaff(staff, '245569534218469376'));

You may try something like this:
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
let item = staff.find(item => item.user == '294597887919128576'); // msg.member.id
if (item) {
console.log(item.text);
}

One another way to do that is:
const inArray = (array, id) => array.filter(item => item.user === id).length >= 1;
const users = [
{
user: '245569534218469356',
text: 'foo'
}, {
user: '245564734218469376',
text: 'bar'
}, {
user: '246869534218469376',
text: 'baz'
}
];
console.log(inArray(users, '246869534218469376')); // true
console.log(inArray(users, '222479534218469376')); // false

Related

getNumber doesn't exists in CommandInteractionOptionResolver discord.js

I'm trying to create a simple add slash command with discord.js, but it seems that interaction.options.getNumber just doesn't exists (look at https://github.com/discordjs/discord.js/blob/main/packages/discord.js/src/structures/CommandInteractionOptionResolver.js#L181)
This is a piece of my code:
...
commands?.create({
name: 'add',
description: 'add two numbers',
options: [
{
name: 'num1',
description: 'The first num',
required: true,
type: DiscordJS.ApplicationCommandOptionType.Number
},
{
name: 'num2',
description: 'The second num',
required: true,
type: DiscordJS.ApplicationCommandOptionType.Number
} ]
})
})
...
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) {
return
}
const { commandName, options } = interaction
if (commandName === 'add') {
console.log(options)
const num1 = options.getNumber('num1')!
const num2 = options.get('num2')!
// idk why but "get" method exists. So I was trying to use it,
// but js says that you couldn't add a string | number | boolean value to an another one
console.log(num1.value + num2.value)
console.log(typeof(num2.value)) // this print "number" btw
interaction.reply({
content: `The sum is ${num1.value}`
})
}
}
There is a solution, but it's intricated:
...
} else if (commandName === 'add') {
console.log(options)
const raw_num1 = options.get('num1')!
const raw_num2 = options.get('num2')!
const num1 = raw_num1.value!
const num2 = raw_num2.value!
interaction.reply({
content: `The sum is ${+(num1) + +(num2)}`
})
}
})

How to get an object value inside another object by a property value in Javascript

I have an object like this
const test = {
'/blogs/architecture':
{
name: 'Architecture',
icon: 'archway',
iconCategory: 'fas',
slug: '/blogs/architecture'
}
}
Now I want find the slug field and I have only the name field. How can I find the slug by the name? please help
Try utilizing Object.values() with Array#find():
const test = {
'/blogs/architecture': {
name: 'Architecture',
icon: 'archway',
iconCategory: 'fas',
slug: '/blogs/architecture'
}
};
const findSlugByName = name => {
return Object.values(test).find(obj => obj.name === name)?.slug;
}
console.log(findSlugByName('Architecture'));
const test = {
'/blogs/architecture': {
name: 'Architecture',
icon: 'archway',
iconCategory: 'fas',
slug: '/blogs/architecture'
},
'/blogs/architecture2': {
name: 'Architecture2',
icon: 'archway',
iconCategory: 'fas',
slug: '/blogs/architecture'
}
}
const searchName = 'Architecture';
let searchResult;
const node = Object.values(test).forEach((node) => {
if(node.name === searchName) {
searchResult = node;
}
});
console.log(searchResult);

I'm getting the empty item instead of a conditionally created item from a map function

In a Reducer of ngRx I'm trying to create a single item from an item matching an if condition, but getting the empty item instead. Please, help!
Here is the Reducer code:
on(rawSignalsActions.changeRangeSchema, (state, { rangeSchemaName }) => ({
...state,
engagementSignal: state.rangeSchemas.map(
item => {
if(item.mapping.rangeSchemaName === rangeSchemaName){
let engagementSignal: EngagementSignal=
{
id:0,
name:'',
metaSignalName:'',
rangeSchemaName:'',
type:2,
mappedGraphSignals:[],
signalInputs:[]
};
engagementSignal.id = item.mapping.id;
engagementSignal.name = item.mapping.rangeSchemaName;
engagementSignal.metaSignalName = item.mapping.metaSignalName;
engagementSignal.rangeSchemaName = item.mapping.rangeSchemaName;
engagementSignal.signalCounts = item.signalCounts;
engagementSignal.type = item.mapping.type;
engagementSignal.mappedGraphSignals = item.abstractSignals.map(
signal => {
let mappedGraphSignal: MappedGraphSignal = {
id:0,
name:'',
totalValues:0,
uniqueUsers:0,
mappedAttitudes:[],
signalRange:[]
};
mappedGraphSignal.id = signal.abstractSignal.id;
mappedGraphSignal.name = signal.abstractSignal.name;
mappedGraphSignal.totalValues = 1234; //dummy values for now
mappedGraphSignal.uniqueUsers = 1234;
mappedGraphSignal.mappedAttitudes = signal.signalAttitudes;
if (signal.numericMappings) {
mappedGraphSignal.signalRange = signal.numericMappings;
} else {
mappedGraphSignal.signalRange = signal.textMappings;
}
return mappedGraphSignal;
}
);
//dummy values for now
engagementSignal.signalInputs = [
{
value: '0',
count: 2376
},
{
value: 'no',
count: 3423
},
{
value: '1',
count: 1264
},
{
value: 'yes',
count: 5423
}
];
return engagementSignal;
}
}
)[0],
linkedRangeSchema: something
})),
I want to get a single item object instead of an array, discarding the rest of array.
When I debug the App, after passing the map function, I got engagementSignal value as:
By applying the filter on array, followed by map function solved the problem!
Here is the working code snippet:
on(rawSignalsActions.changeRangeSchema, (state, { rangeSchemaName }) => ({
...state,
engagementSignal: state.rangeSchemas.filter(item =>item.mapping.rangeSchemaName === rangeSchemaName).map(
item => {
let engagementSignal: EngagementSignal=
{
id:0,
name:'',
metaSignalName:'',
rangeSchemaName:'',
type:2,
mappedGraphSignals:[],
signalInputs:[]
};
engagementSignal.id = item.mapping.id;
engagementSignal.name = item.mapping.rangeSchemaName;
engagementSignal.metaSignalName = item.mapping.metaSignalName;
engagementSignal.rangeSchemaName = item.mapping.rangeSchemaName;
engagementSignal.signalCounts = item.signalCounts;
engagementSignal.type = item.mapping.type;
engagementSignal.mappedGraphSignals = item.abstractSignals.map(
signal => {
let mappedGraphSignal: MappedGraphSignal = {
id:0,
name:'',
totalValues:0,
uniqueUsers:0,
mappedAttitudes:[],
signalRange:[]
};
mappedGraphSignal.id = signal.abstractSignal.id;
mappedGraphSignal.name = signal.abstractSignal.name;
mappedGraphSignal.totalValues = 1234; //dummy values for now
mappedGraphSignal.uniqueUsers = 1234;
mappedGraphSignal.mappedAttitudes = signal.signalAttitudes;
if (signal.numericMappings) {
mappedGraphSignal.signalRange = signal.numericMappings;
} else {
mappedGraphSignal.signalRange = signal.textMappings;
}
return mappedGraphSignal;
}
);
engagementSignal.signalInputs = [
{
value: '0',
count: 2376
},
{
value: 'no',
count: 3423
},
{
value: '1',
count: 1264
},
{
value: 'yes',
count: 5423
}
];
return engagementSignal;
}
)[0],
linkedRangeSchema: something
})),

Deleting JSON object based on attribute

I am working with React, I have got a variable named newtreeData, which looks like:
var newTreeData = {
name: submitted_title,
resource_link: submitted_resource_link,
details: submitted_details,
uuid: submitted_uuid,
website_image: submitted_website_img,
children: [
{
name: "Edit and save",
resource_link: "uh",
uuid: uuid.v4(),
details: "hi",
website_image:
"https://cdn3.iconfinder.com/data/icons/harmonicons-06/64/plus-circle-512.png",
children: [{...}, {}, ...]
},
{
name: "Edit and save",
resource_link: "uh",
uuid: uuid.v4(),
details: "hi",
website_image:
"https://cdn3.iconfinder.com/data/icons/harmonicons-06/64/plus-circle-512.png"
}
]
};
The line children: [{...}, {}] is just representing that newTreeData's children can have children which can have children...
Anyways, I wrote a method name findUUIDthenDelete which should do in pseudocode: if(object.uuid == toFindUUID) then delete object, and here's the full code for findUUIDthenDelete:
findUUIDthenDelete = (orig_data, to_delete_uuid) => {
var targetIsFound = false;
if (orig_data.uuid == to_delete_uuid) {
targetIsFound = true;
}
if (targetIsFound == false) {
if (orig_data.children === undefined) {
} else {
//if target not found, run recursion
orig_data.children.map(eachChildren =>
this.findUUIDthenDelete(eachChildren, to_delete_uuid)
);
}
} else {
console.log(orig_data, "this is the child ");
console.log(orig_data.parent, "is found, deleting its parent");
delete orig_data
}
};
As you can see this method is two parts: first I locate the object which has the uuid that we are trying to seek (potentially with some recursions), then delete the object. However, right now I am getting the "delete in local variable strict mode blah blah" error because of doing delete orig_data. Any insights to any workarounds to that error or some totally new way of tackling this? Also sincere apologies if there is an obvious solution I am out of mental energy and unable to think of anything algorithmic at the moment.
This should do it:
function findUUIDthenDelete(tree, uuid) {
if (!tree.children) return;
tree.children = tree.children.filter(c => c.uuid !== uuid);
tree.children.forEach(c => findUUIDthenDelete(c, uuid));
}
Should be pretty self-explanatory.
First, if the current node has no children, exit right away.
Next, potentially remove a child from the children array if the uuid matches using filter().
Finally, recursion.
Ok I'll admit this turned out to be more complicated than I thought, but the solution below will work if you can use Immutable. Essentially it walks your objects and collects the path to find the object that has the uuid and then once it has done that, it removes it.
const testMap = Immutable.fromJS({
uuid: 1,
children: [{
uuid: 2,
children: [{
uuid: 3,
children:[{
uuid: 8
}]
},
{
uuid: 4
},
{
uuid: 5
},
]
},
{
uuid: 7
}]
});
function findPath(checkMap, uuid, pathMap, currentIndex) {
if (checkMap.has('uuid') && checkMap.get('uuid') === uuid) {
const updatePathMap = pathMap.get('path').push(currentIndex);
return new Immutable.Map({
found: true,
path: pathMap.get('path').push(currentIndex)
});
} else {
if (checkMap.has('children') && checkMap.get('children').size > 0) {
for (let i = 0; i < checkMap.get('children').size; i++) {
const child = checkMap.get('children').get(i);
const checkChildPath = findPath(child, uuid, pathMap, i);
if (checkChildPath.get('found') === true) {
let updatePath = checkChildPath.get('path').push('children');
updatePath = updatePath.push(currentIndex);
return new Immutable.Map({
found: true,
path: updatePath
});
}
}
}
return pathMap;
}
}
const testPath = findPath(testMap, 7, new Immutable.Map({
found: false,
path: new Immutable.List()
}), 0);
console.info(testPath);
const testPath2 = findPath(testMap, 8, new Immutable.Map({
found: false,
path: new Immutable.List()
}), 0);
console.info(testPath2);
if (testPath2.get('found') === true) {
const path = testPath2.get('path');
if (path.size === 1 && path.get(0) === 0) {
// Your highlest level map has the uuid
} else {
const truePath = path.shift();
const cleanedUpMap = testMap.removeIn(truePath);
console.info(cleanedUpMap);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>

Not able to understand error in promise chain in ES6

I have a series of asynchronous operations in my Backend code . I have doing backend coding in node js .
My code is something like this
db.users
.findAll({
where: condition,
duplicating: false,
attributes: userAttributes,
include: inclusion,
group: ['users.id', 'organizationEntries.id'],
order: [['organizationEntries', 'createdAt', 'DESC']]
})
.then(users => {
let result = users.map(c => {
let output = {
user_id: c.id,
name: c.name,
mobile: c.mobile,
mobile_alternate: c.mobileAlternate,
email: c.email,
gender: c.gender,
dob: c.dob,
image: Utils.getImageUrl(c.image),
entry_id: c.organizationEntries[0].id,
doj: c.organizationEntries[0].fromDate,
status: c.organizationEntries[0].status
};
if (isPlayer && c.dataValues.amount) {
output.due_amount = c.dataValues.amount.toFixed(2);
}
let arenaPromise;
if (!isPlayer) {
output.address_text = addressController.prepareAddressText(c.address);
output.address = addressController.prepareAddressJson(c.address);
if (c.organizationEntries[0].arenaIds)
db.arenas
.findAll({
attributes: ['name'],
where: {
id: {
[Op.in]: c.organizationEntries[0].arenaIds
},
organizationId: req.ORG_ID
}
})
.then(arenas => {
console.log(arenas);
output.arenas = arenas.map(a => {
let arena = {};
arenas.forEach(element => {
arena.name = element.name;
// console.log(arena.name);
});
console.log(arena);
return arena;
});
console.log(output);
// res.send(output);
});
}
return output;
});
res.send(result);
All the things are working fine but in the last then block where I am trying to add arenas in the output object .
.then(arenas => {
console.log(arenas);
output.arenas = arenas[0].name;
output.arenas = arenas.map(a => {
let arena = {};
arenas.forEach(element => {
arena.name = element.name;
// console.log(arena.name);
});
console.log(arena);
return arena;
});
Actually what is happening I am able to fetch arenas data from database
but after fetching it is not assigning the arenas in output object .
I am learning promise chain so anyone can please help me or give me some hint

Categories