Javascript Equalize Element From Array - javascript

Guys I want to get an element from array. Here:
Follower:
{ follower:
[ 5edfe8f3bfc9d677005d55ca,
5edfe92fbfc9d677005d55cc,
5ee2326cc7351c5bb0b75f1a ],
user id:
5edfe92fbfc9d677005d55cc
The process:
if(follower == user){
console.log("sdasdsad")
}else{
console.log("no")
}
But when I do it it always returns as no.
Also this is the codes of===> Nodejs Follow System Not Working Properly
It is a nodejs project. So please look at the above link.
When I do
if(follower.includes(user)){
It gives the error of:
TypeError: Cannot read property 'includes' of null
And when I try to change some I get this error:
TypeError: takip.includes is not a function
Guys so thats why I say please look at the above code.
So how to equalize them?

As other peoples said earlier the follower itself is a property which its value is an array itself, so if you want to check whether an item exists within it or not you can check it with includes(), if it exists it will return true otherwise it will return false.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if (follow.follower.includes(user)) {
console.log("sdasdsad")
} else {
console.log("no")
}
But if you looking to find the exact position of the item within that array you can find it with indexOf(). If the item does not exist within the array it will return -1, otherwise, it will return the index of that item within the array.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
console.log(follow.follower.indexOf(user));

You are trying to compare a string to an array so it will never pass the if statement.
If you change your if to be if ( follower.includes(user)) { then it will search the array for the string.
var follower = [
'5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
var user = '5edfe92fbfc9d677005d55cc'
// This will always fail as follower is an array not a string
if (follower.includes(user)){
console.log("sdasdsad")
} else {
console.log("no")
}
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Looks like follower is a property. You can use this solution:
objectName.follower.forEach(item =>
if (item == user) console.log(`${item} is the answer`);
);
This way, javascript will go through all of the elements in the array and print it out if it is matching with your user variable.
You can also use for loop or while loop for the same process, however, since you're using an array, forEach will be much more useful.
If this was not your question and I misunderstood your question, let me know, I'll see if I can help.

I hope this helps
var obj = {
follower: [ '5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
};
var userId = '5edfe92fbfc9d677005d55cc';
function searchUser(object, user){
if(obj.follower.includes(user)){
return object.follower.filter(x => x == user);
} else {
return 'no';
}
};
console.log(searchUser(obj, userId));

You can use Array.protorype.some() to check if user exists in the follower array.
const obj = {
follower: [
"5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if(obj.follower.some(item => item === user)) {
console.log("found")
} else{
console.log("no")
}
You can also get the item with Array.protorype.find() with the same way as above, just assign it to a variable
Array.prototype.some
Array.prototype.find

Related

Check Javascript nested obj value exists with unknown key

The following is used to build up a object array:
var users = {};
var user = {};
user[socket.id] = data.username;
if(users[data.roomname]){
// Room already exists - check user already exists
// if data.username does not value exist is users then:
users[data.roomname].push(user);
}
else{
// New room
users[data.roomname] = [user];
}
Over a few iterations we get something like this:
console.log ( 'Users: ', users );
users { RoomABC:
[ { YidwzgUHPHEGkQIPAAAD: 'Mr Chipps' },
{ 'JG-gtBMyPm0C1Hi1AAAF': 'Mr T' },
{ '2JFGMEdPbgjTgLGVAAAH': 'Mr Chipps' }, ] }
The issue is trying to ensure that each username is unique, so Mr Chipps should not be added again if that name already exists.
The examples I have seen Assume the keys are known. I have tried a number of things including some, indexOf but I am not able to get a simple 'does UserX already exist' to work.
The following is the latest block of code I tried to only add the user if not already present in the obj array. This works, but it seems very clunky to me; nested loops to get at the correct level to check the value and set a counter if a match found, then check the counter to decide if a match was found or not:
if(users[data.roomname]){
// Room already exists - check user already exists
let found = 0;
// Nested loop - seems a little clunky but it works
Object.keys(users[data.roomname]).forEach(key => {
Object.keys(users[data.roomname][key]).forEach(key2 => {
if ( users[data.roomname][key][key2] === data.username ) {
found++;
}
});
});
if ( found == 0 ) {
users[data.roomname].push(user);
}
}
I keep thinking surely there is neat one-liner that can do this check for the existence but I cant get any to work.
You could check the values instead of using the keys and exit early if a name is found
if (users[data.roomname]) {
if (!Object.values(users[data.roomname]).some(v => Object.values(v).some(n => n === data.username))) {
users[data.roomname].push(user);
}
}

Why does comparing a property to the author.id not work?

So here is my current code for a currency system. This code works to add the new user information in. Obviously this will keep adding the people that are already in it.
if (!currency[message.author.id]) {
currency.push({id: message.author.id, coins: 0});
}
if I change it to this one, nothing happens. It seems there's something wrong with this comparison and I'm not sure what it is considering it worked for other things I have used.
if (!currency[0].id == message.author.id) {
currency.push({id: message.author.id, coins: 0});
}
This looks right to me as it's getting the id property of the first element and checking if they're the same. When I run the code it just doesn't do anything. No errors and nothing in the json file I'm using to store it. It does this when the array is empty and does it when I have an id property in there.
Is this not possible? I don't like having to set it up using the first way because I'd like to be able to access everyone's currency if needed to add or take away without having to do it one person at a time.
I think it should be !==:
if (currency[0].id !== message.author.id) {
currency.push({id: message.author.id, coins: 0});
}
or should be wrapped in brackets:
if (!(currency[0].id == message.author.id)) {
currency.push({id: message.author.id, coins: 0});
}
It sounds like you probably want a data structure that's an object, not an array, so that you can have arbitrary key-value pairs - have the key be the message.author.id.
const currency = {};
// ...
const { id } = message.author;
if (!currency[id]) {
currency[id] = { id, coins: 0 };
} else {
// this author was already inserted - do something else here, if desired
// current[id].coins += coinChangeAmount; // for example
}
Your original code sounds like it's misusing an array as an object, and the currency[0].id == message.author.id will only check the [0]th element of the array, rather than iterating over all possible elements and looking for an ID match.

how to check: if array includes specific text properly?

I am struggling with doing an array search that includes a piece of text that must include back slashes in it. I have tried includes(''); negating includes(''); and also trying similar using indexOf('').
I have a simple array, with at maximum four values; typically it has two, here is how it typically looks:
{tks: Array(2)}
tks: Array(2)
0: "https://mycoolwebsite.net/arcgis/rest/services"
1: "https://mycoolwebsite.com/arcgis/rest/services"
length: 2
__proto__: Array(0)
__proto__: Object
Here are the simple checks I'm trying to do: My second check with *includes* 'wdt' text seems to be working so I assume it's something with the backslashes. Anyway I can handle this? I'm perplexed why my if and else both get hit with the first check below using back slashes... I added the negating on the else to double check.. with and without that in the else, else is always hit.
// right before doing the search I am building the array, just to add more context
for (let i = 0; i < coolObj.length; i++) {
if (coolObj[i].url){
tr = coolObj[i].url;
tks.push(tr);
console.log({tks});
}
}
console.log({tks}); // consoles as I have included above ^
if (tks.includes('/arcgis/rest/services')) {
console.log({tks});
} else if (!tks.includes('/arcgis/rest/services')) {
console.log({tks});
console.log('does not include correct url');
aT = '/arcgis/rest/services';
lP = false;
filterAt(aT);
}
if (tks.includes('wdt')) {
console.log({tks});
}else {
console.log({tks});
wT = 'wdt';
filterWt(wT);
}
From the MDN docs: The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
You have to test the strings using String.prototype.includes within the array elements thus:
const arr = ["https://mycoolwebsite.net/arcgis/rest/services", "https://mycoolwebsite.com/arcgis/rest/services"];
arr.forEach(el => {
if (el.includes('/arcgis/rest/services')) {
console.log(el, ': includes url');
}
else {
console.log('does not include correct url');
}
if (el.includes('wdt')) {
console.log(el, ': includes wdt');
} else {
console.log('does not include correct wdt');
}
});

Add an object to JSON

I have a settings.json file that contains following data (where 123456789 is a distinct user id):
{
"123456789":
{"button_mode":true}
}
So what I need to do is push a similar id: {button_mode: value} object to this JSON file in case there's no entry for current user's id. I tried to use lcSettings.push() but obviously it did not work since I have an object, not an array. When I put square brackets instead of curly ones to make it an array, my code doesn't do anything at all.
Here's a snippet of it (Node.js):
var lcSettings = JSON.parse(fs.readFileSync('./settings.json', 'utf8'));
var currentUser = id;
if (lcSettings.hasOwnProperty(currentUser)) {
// in case settings.json contains current user's id check for button_mode state
if (lcSettings[currentUser].button_mode == true) {
// if button_mode is on
} else
if (lcSettings[currentUser].button_mode == false) {
// if button_mode is off
}
} else {
// in case there's no entry for current user's id
// here's where I need to push the object for new user.
}
fs.writeFileSync('./settings.json', JSON.stringify(lcSettings))
Does anybody have ideas on how it can be implemented? Any help appreciated.
You can use bracket notation to add a dynamic property to an object:
lcSettings[id] = { button_mode: false };
You may also want to verify that settings.json is not empty otherwise the JSON.parse() will fail. In this case, you would want to initialize lcSettings to an empty object (lcSettings = {}) so the above will work.
To 'push' elements to an object you simply define them, as in
object['123456789'] = { button_mode: true };

Remove element in Typescript Interface List when entry present, always displaying negative index

I have an interface:
export interface ISchoolsPreview {
// Shared
AgeID: string;
School_name?: string;
}
I have a function triggered by a change in a Checkbox:
onChange(code: string, name: string, check: boolean): void {
const tempPreview: ISchoolsPreview = {AgeID: code, School_name: name};
if (check) {
this.schoolsPreview.push(tempPreview);
} else {
//This is where the error lies
const index = this.schoolsPreview.indexOf(tempPreview);
if (index > -1) {
this.schoolsPreview.splice(index, 1);
}
}
}
Check is defined by whether the checkbox was checked or uncheched. If checked it adds a new element of ISchoolsPreview to schoolsPreview. This works and when I step through it shows up and displays correctly on my front end.
However when I uncheck a checkbox, the indexOf(tempPreview) always returns -1 even if I am passing the same entry.
How do I correctly remove an element from my Interface List
You should always find the index of the object based on some property in the object rather than using the whole object itself as follows.
const index = this.schoolsPreview.findIndex((obj) => obj['Property'] === code);
If you thing you will have duplicate codes in the array, then you might have to generate unique ids for each objects and search based on that Id.
Note: I am not sure on this, but passing object to index while return true only if the object references to the same memory. If its a new object you are trying to find, which is in new memory, it might return false. Someone can correct me on this.
I have fixed this by changing:
const index = this.schoolsPreview.indexOf(tempPreview);
to:
const index = this.schoolsPreview.findIndex(s => s.AgeID === code);

Categories

Resources