ajax-like search with internal list - javascript

I apologize ahead of time if the title was worded oddly!
I want to do an ajax-like search on a list I have on the client side (i.e. a list of friends). The list would look like this:
var friendList = new Array [
{
name: "Mark",
email: "mark#gmail.com",
birthDate: "01/01/1980"
},
{
name: "Steve",
email: "steve#gmail.com",
birthdate: "02/02/1980"
},
{
name: "Frank",
email: "frank#gmail.com",
birthDate: "03/03/1980"
}
]
How would I search letter by letter with an input field like so:
<input type="search" id="searchFriends" />
Thanks!

Related

JavaScript (ReactJS) comparing two Objects

I have an object with users:
const data = [
{
name: "John",
lastName: "Doe",
email: "stefa#gmail.com",
password: "123",
following: [{ id: "113"}, { id: "111" } }],
id: "112",
},
{
name: "Jane",
lastName: "Doe",
email: "dusica#gmail.com",
password: "123",
following: [{ id: "112" }],
id: "113",
},
{
name: "Mark",
lastName: "Twain",
email: "marko#gmail.com",
password: "123",
following: [],
id: "111",
},
];
As you can see all users have an array named "following", and that array contains id's of users which the user follows. I want to access that array "following" to find out which users are not followed. Let's say that we want to check the "following" array of the first user John Doe with id="112".
const followers = [];
let suggestions = null;
props.users.forEach((user) => {
if (user.id === '112') {
user.following.forEach((item) => {
followers.push(item);
});
}
});
followers.map((item) => {
suggestions = props.users.map((user) => {
if (user.id !== item.id && user.id !== '112) {
console.log(item.id);
return <div>something</div>;
}
});
});
I tried something like this, but the result is not what i expected to be. As i said, i want to return users that are not followed and render them because i want them to be visible so the user can follow them. I hope that i was understandable enough. Thanks.
It's a negative comparison.
So you want to filter out all users that a user IS following.
You can loop through each user and compare it against the following array. If the following array contains the user then don't show it.
const notFollowing = allUsers.filter(user =>
!currentUser.following.some(({ id }) => id === user.id)
);

In JavaScript, how can I store an array of object value into string variable?

I have this object with the following data that I need to store in a variable:
user: [
{
firstname: 'John',
lastname: 'Doe',
roles: [
{
roleId: 18,
displayText: 'accountant',
description: 'accountant'
}
]
}
]
I am looping through this object as such:
let selectedRole = user.roles.map((role, index) => {
return role.displayText
})
selectedRole returns me the following output: ["accountant"]
For example:
John Doe has only 1 role assigned to him -> account
Sam Williams has 3 roles assigned -> program manager, account, admin
let's say if I click on Sam William's details then I want to see all the roles that I assigned to him in not comma separated but in the following layout:
Role 1: program manager
Role 2: account
Role 3: admin
If you want to get all elements of the array as a delimited string, you can use Array.prototype.join: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
let selectedRoles = user.roles.map((role, index) => {
return role.displayText
});
let rolesString = selectedRoles.join();
If selectedRoles is ['accountant', 'admin'] then the value of rolesString will be accountant, admin. The parameter of join is optional, but its value is the delimiter (comma is default).
EDIT
So if you don't want them as one string, but instead you want to display them individually on the screen. How are you displaying them? Are you using Angular or some other library/framework, or are you using plain JavaScript?
If you're using Angular, for example, you'll use its mechanisms for looping over a collection. So:
<ul *ngFor="let role of selectedRoles; let idx = index">
<li>Role {{idx}}: {{role}}</li>
</ul>
If you don't need an array, but just the string, then don't use .map:
const user = [
{
firstname: 'John',
lastname: 'Doe',
roles: [
{
roleId: 18,
displayText: 'accountant',
description: 'accountant'
}
]
}
];
const selectedRole = user[0].roles[0].displayText;
console.log(selectedRole);
If you want to join all roles into a string, use .join by whatever delimiter you want:
const user = [
{
firstname: 'John',
lastname: 'Doe',
roles: [
{
roleId: 18,
displayText: 'accountant',
description: 'accountant'
},
{
roleId: 20,
displayText: 'somethingElse',
description: 'somethingElse'
}
]
}
];
const selectedRole = user[0].roles.map((r, i) => `Role ${i + 1}: ${r.displayText}`).join('\n');
console.log(selectedRole);

Algolia: search for multiples values in each fields with AND clause

I would like know if i can query different values in each field
returning values that only match with the search like AND condition. I tried use search in multpile indexes, but it return values like OR condition.
Example:
my index contains:
[
{
firstName: 'Alisson',
lastName: 'Oliveira',
},
{
firstName: 'Alex',
lastName: 'Oliver',
},
{
firstName: 'Daniel',
lastName: 'Costa',
}
]
my query would be:
index.search(query: { firstName: 'Al', lastName: 'Oliv' })
the response espected:
[
{
firstName: 'Alisson',
lastName: 'Oliveira',
},
{
firstName: 'Alex',
lastName: 'Oliver',
}
]
Someone know if is possible in the algolia?
Based on your example it sounds like your end-user would type the query: "Al Oliv" and you would expect the two records shown above to return.
To do this, you would change the default settings from prefixLast to prefixAll. You can do this in the Dashboard:
By default Algolia only uses the last word as a prefix. If you make the change above the query will return the expected results:

Iterating through object properties/keys

I'm just starting to learn coding, and i came across this question that i could not understand.
"The second function we'll add will be called search, and it will take a first name as an argument. It will try to match the first name it receives to any of the first names in our friends contact list. If it finds a match, it will log our friend's contact information (firstName, lastName, number, address) to the console."
variables are define as follows :
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
the answer is as follows :
var search = function(name) {
for(var key in friends) {
if(friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
};
could someone better explain how did the var "key" came about ? and why can't i just input friends.firstName === name, console.log(friends.name), return friends.name ??
would appreciate if someone could explain thank you.
From OP's comment:
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
friends is a nested object which can also be represented like so:
friends = {
bill: {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
},
steve: {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
}
}
The for..in loop iterates over all keys in the friends object, with the variable key in your case.
why can't i just input friends.firstName === name, console.log(friends.name), return friends.name ??
Because, to do that, you need to have firstName or name as a property in friends. Since those properties are nested inside (name is not event inside the nested objects), there was a for..in loop used.
You have an object friends that has 2 properties bill and steve (those are the keys). Calling friends.bill will return you an object (the value) with firstname, lastname, number, address. You need to iterate all the properties of your object friends to find the one you need
You can use Object.values(obj)
var firstNameInput = "Steve";
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
//Iterates all the friends
Object.values(friends).forEach(function(f){
//Compare the property "firstname" with the input
if(f.firstName === firstNameInput){
//Friend found
console.log(f);
return;
}
});

A program in javascript using constructors

<script>
<!-- A program to search for a friend from an object -->
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "205-555-1111",
address:["One Microsoft Day","Redmond","WA","90852"]
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "408-555-2222",
address: ["One Infinite Loop", "Cupertino", "CA", "95014"]
},
wendy: {
firstName: "Wendy",
lastName: "Johnson",
number: "510-555-3333",
address: ["3555 Anyplace drive","New York", "NY","11001"]
}
}
alert(friends["steve"].lastName);
alert(friends.length);
var search = function(name)
{
document.write(name);
for (var nameSearch in friends)
{
alert(nameSearch.firstName);
if(friends[nameSearch].firstName===name)
{
return friends[nameSearch];
}
}
}
search("Wendy");
</script>
Theres a couple things wrong with your code:
Objects do not have a length property so the second alert for friends.length will not work
When you're using for in you are referencing the key of the object, so in this case it will be bill, steve, or wendy so when you do nameSearch.firstName it will be undefined since nameSearch is a string
Finally, the reason that your example is failing is because you're searching against case-sensitive text. wendy != Wendy. Also please keep in mind that triple equals checks the constructor.
To fix your code, you can try just lower-casing all of your search text:
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "205-555-1111",
address:["One Microsoft Day","Redmond","WA","90852"]
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "408-555-2222",
address: ["One Infinite Loop", "Cupertino", "CA", "95014"]
},
wendy: {
firstName: "Wendy",
lastName: "Johnson",
number: "510-555-3333",
address: ["3555 Anyplace drive","New York", "NY","11001"]
}
};
var search = function(name) {
for (var nameSearch in friends) {
if(friends[nameSearch].firstName.toLowerCase()===name.toLowerCase()) {
return friends[nameSearch];
}
}
}
console.log(search("wendy"));

Categories

Resources