Can't get value of array - javascript

Still can't understand my mistake with this code.
All what I want it - via prompt get all list of users (name / surname)
function UserList() {
let users = [];
while (true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
users.push(response.split(' '));
}
return users;
}
function User() {
this.name = userList[0];
this.surname = userList[1];
this.regDate = new Date;
for (i = 0; i < userList.length; ++i) {
console.log('Name: ' + this.name + ' Surname: ' + this.surname + '. Date of registration : ' + this.regDate)
}
}
let userList = new UserList();
let user = new User();
And I faced with a misunderstanding why I cant get first word of prompt despite I put users.push (response.split(' ')).
userList [0] - shows first index of array instead first word.
And second I want to get all list of users in console.log but instead it I get the same string depending on length of array

userList[0] in the function User will return an array: ['name', 'surname'].
To get the first name for example, you need to use this.name = userList[i][0]
function UserList() {
let users = [];
while (true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
users.push(response.split(' '));
}
return users;
}
function User() {
for (var i = 0; i < userList.length; ++i) {
this.name = userList[i][0];
this.surname = userList[i][1];
this.regDate = new Date;
console.log('Name: ' + this.name + ' Surname: ' + this.surname + '. Date of registration : ' + this.regDate)
}
}
let userList = new UserList();
let user = new User();

You are pushing an array in an other array, so your index is not correct (array looks like this: [["firstname", "lastname"]]). You could spread the items when pushing using the spread operator (...), you could also flatten the array using flat().
Also when creating a date, use new Date().
function UserList() {
let users = [];
while (true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
users.push(...response.split(' ')); // flatten
}
return users;
}
function User() {
this.name = userList[0];
this.surname = userList[1];
this.regDate = new Date(); // ()
console.log('Name: ' + this.name + ' Surname: ' +
this.surname + '. Date of registration : ' + this.regDate)
}
let userList = new UserList();
let user = new User();
Using flat()
return users.flat();
Edit
I actually understood the question wrong (thought you only wanted 1 user), the other answer should be correct and makes more sense.

UserList shouldn't be a constructor. It should just be a function that returns an array of names.
You shouldn't be iterating over the list of users within User. You should then be iterating over the array creating one new User on each iteration which should be generated from a constructor. You can just pass in each name from the array and build an new object.
function getNames() {
const users = [];
while (true) {
const response = prompt('Please, enter your first and last names');
if (response == null) break;
users.push(response.split(' '));
}
return users;
}
// Pass in a user name from the array as an argument
// It's array so we can destructure the first and last name
// immediately
function User([first, last]) {
this.first = first;
this.last = last;
this.regDate = new Date();
this.message = `Name: ${this.first}. Surname: ${this.last}. Date of registration: ${this.regDate}.`;
}
// Iterate over the array generated by `getUsers`
// and for each name create a new user.
for (let name of getNames()) {
console.log(new User(name));
}
Additional documentation
Destructuring assignment

Related

Making an output of frends names instead of IDs

Can somebody help me with this, i m new to javaScript and i m stuck at this point.I made an output of certain object within my array ,that output is writing a persons values, within that object(Osoba) there is an array of his friends and all values inside are IDs of each person, http://prntscr.com/i9m2ti how can i make that ID of a friend array ( within the object ) to be a first name and surname of that person which id is in array and when i want to output a certain object so there will be friends[ their names instead of IDs], can someone write me down how can i do that. Thanks for understanding.
class Osoba{
constructor(id,firstName,surname,age,gender,friends){
this._id = id ;
this._firstName = firstName;
this._surname = surname;
this._age = age;
this._gender = gender;
this._friends = friends;
}
get id() {
return this._id;
}
set id(id){
this._id = id;
}
get firstName() {
return this._firstName;
}
set firstName(firstName){
this._firstName = firstName;
}
get surname() {
return this._surname;
}
set surname(surname){
this._surname = surname;
}
get age() {
return this._age;
}
set age(age){
this._age = age;
}
get gender() {
return this._gender;
}
set gender(gender){
this._gender = gender;
}
get friends() {
return this._friends;
}
set friends(friends){
this._friends = friends;
}
}
var osobe = []; // my array
$(function() {
$.getJSON('https://raw.githubusercontent.com/Steffzz/damnz/master/
data.json' , function(data)
{
var json = jQuery.parseJSON(JSON.stringify(data));
for(person of json)
{
var id = person['id'] ;
var firstName = person['firstName'] ;
var surname = person['surname'] ;
var age = person['age'] ;
var gender= person['gender'] ;
var friends = person['friends'] ;
var x = new Osoba(id,firstName,surname,age,gender,friends);
osobe.push(x); //filling array with objects and their values
}
console.log(osobe);
document.write(JSON.stringify(osobe[0])) //output of a certain object
})
});
Assuming json is an array and contains all people you can map over friends array and find the person with that id: person['friends'].map( and json.find(function(person){person.id===friendId});.
Then return an object containing that person's first and last name:
console.log("json is:",JSON.stringify(json,undefined,3));
var friends = person['friends'].map(
function(friendId){
console.log("friendID is:",friendId);
var friend = json.find(function(person){return person.id===friendId;});
console.log("friend is:",JSON.stringify(friend,undefined,2));
return {
firstName:friend.firstName,
surname:friend.surname
}
}
);
Now if that "does not work" could you please specify the output of the logs, any errors and expected results versus actual results?
UPDATE FULL CODE
Since the json is all your data you can pass that into your Osoba constructor. The friends getter will use the data to create an array Osaba items that will have data and friends that will create an array of Osaba ...
class Osoba {
constructor(id, firstName, surname, age, gender, friends, data) {//added data
this._id = id;
this._firstName = firstName;
this._surname = surname;
this._age = age;
this._gender = gender;
this._friends = friends;
this._data = data;//data has all the people
}
get id() {
return this._id;
}
set id(id) {
this._id = id;
}
get firstName() {
return this._firstName;
}
set firstName(firstName) {
this._firstName = firstName;
}
get surname() {
return this._surname;
}
set surname(surname) {
this._surname = surname;
}
get age() {
return this._age;
}
set age(age) {
this._age = age;
}
get gender() {
return this._gender;
}
set gender(gender) {
this._gender = gender;
}
//modified friends getter returning an array of Osoba items
get friends() {
var me = this;
return this._friends.map(
function (friendId) {
var friend = me._data.find(function (person) { return person.id === friendId; });
return new Osoba(
friend.id,
friend.firstName,
friend.surname,
friend.age,
friend.gender,
friend.friends,
me._data
);
}
);
}
set friends(friends) {
this._friends = friends;
}
}
$.getJSON('https://raw.githubusercontent.com/Steffzz/damnz/master/data.json')
.then(
json => {
var people = json.map(
person =>
new Osoba(
person.id,
person.firstName,
person.surname,
person.age,
person.gender,
person.friends,
json
)
);
//you can keep getting friends now, because Osoba is
// creating new Osoba objects based on id's and data you pass in
console.log(people[0].friends[0].friends[0].friends[0]);
}
);
instead of
var friends = person['friends'] ;
try
var friends = [];
var friendIDs = person['friends'] ; //retrieve friendIDs
for(friendID of friendIDs) { //loop over friendIDs
var friend = json[friendID]; //get friend dataset out of the json
friends.push(friend['firstName']); // add friend dataset to friends array
}
I assume here that those friends are in that json aswell. and that the ids represent that index inside that array. if the indexes aren't those ids this won't work. feel free to comment if thats the case and i'll edit my answer.
If i understand correctly you just want to use id for id, firstname, and lastname. so just pass id 3 times instead of firstname and lastname:
var x = new Osoba(id,id,id,age,gender,friends);
~~~~
Ok so what you want is actually that the id property within each friend object be the first and last name of the friend instead of an idea code. So it's basically just the opposite of what i suggested earlier. All you have to do is manipulate what you push to id. There's no obligation on it being the id from the json.
so in your case:
for(person of json){
var id = person['firstName'] + "" + person['surname']; // line to change.
var firstName = person['firstName'] ;
var surname = person['surname'] ;
var age = person['age'] ;
var gender= person['gender'] ;
var friends = person['friends'] ;
var x = new Osoba(id,firstName,surname,age,gender,friends);
osobe.push(x); //filling array with objects and their values
}

Get multiple values with local storage

I'd like to retrieve the name and the date of created tasks. I managed to put the value taskMessage in local storage, but I don't know how to add taskName as well. This is the code I currently have :
$(document).ready(function () {
var i = 0;
for (i = 0; i < localStorage.length; i++) {
var taskID = "task-" + i;
$('.task-container').append("<li class='item-content' id='" + taskID + "'>" + localStorage.getItem(taskID) + "</li>");
}
$('.floating-button').on('click', function () {
myApp.prompt('', 'Add Task', function (task) {
if (task !== "") {
myApp.prompt('', 'Choose time', function (time) {
var d1 = new Date();
d1.setHours(time, 0, 0, 0);
var hour = d1.getHours();
if (time > 0 && time < 25) {
var d2 = new Date();
var currenttime = d2.getHours();
if (time > currenttime) {
var taskID = "task-" + i;
var taskMessage = hour;
var taskName = task;
localStorage.setItem(taskID, taskMessage);
var newtask = '<li class="item-content ' + taskID + '"><div class="item-inner"><div class="item-title" >' + taskName + '</div><div class="item-after"> ' + taskMessage + ':00</div> </div></li>';
var taskitem = $('#' + taskID);
$('.task-container').append(newtask);
}
else {
myApp.addNotification({
message: 'Please choose a valide time period'
});
}
}
else {
myApp.addNotification({
message: 'Please choose a value between 1 and 24'
});
}
});
}
else {
myApp.addNotification({
message: 'Please enter a valid name'
});
}
});
});
});
First you should get the data into a variable
var getData =
{
"firstData":"data1",
"secondData":"data2",
"thirdData": "data3"
}
Then you can set the above data's in localStorage...
localStorage.setItem('dataKey', JSON.stringify(getData ));
Then get....
var val = localStorage.getItem('dataKey');
Enjoy!!!
If you want to store two different values in localStorage then you can do somrthing like this :
setItem in localStorage two times with different keys.
localStorage.setItem("message", taskMessage);
localStorage.setItem("name", taskName);
Store both the values in an object.
var obj = {
"message": taskMessage,
"name": taskName
}
var val = localStorage.setItem("task", obj);
typeof val: string
Value of val: [object Object]
setItem method convert the input to a string before storing it.
Try this :
// Put the object into storage
localStorage.setItem('task', JSON.stringify(obj));
// Retrieve the object from storage
var val = localStorage.getItem('obj');
console.log('retrievedValue: ', JSON.parse(val));
You can easily store values in localstorage using following example.
//Save the values to Localstorage
localStorage.setItem('first','firstvalue');
localStorage.setItem('second','secondvalue');
//Retrieve the values from localstorage
localStorage.getItem('first')
//"firstvalue"
localStorage.getItem('second')
//"secondvalue"
localStorage saves item key&value as string,so you call setItem with an object/json object,you must serialize json to string by JSON.stringify() method.when you get value you need parse string as json object using JSON.parse() method.
Test
test(`can't retrieve json from localStorage if raw json data saved`, () => {
localStorage.setItem('foo', {foo: 'bar'});
expect(localStorage.getItem('foo')).toEqual('[object Object]');
});
test(`retrieve json value as string from localStorage`, () => {
localStorage.setItem('foo', JSON.stringify({foo: 'bar'}));
let json = JSON.parse(localStorage.getItem('foo'));
expect(json.foo).toEqual('bar');
});
test(`key also be serialized`, () => {
localStorage.setItem({foo: 'bar'}, 'value');
expect(localStorage.getItem('[object Object]')).toEqual('value');
});
test('supports bracket access notation `[]`', () => {
localStorage.setItem('foo', 'bar');
expect(localStorage['foo']).toEqual('bar');
});
test('supports dot accessor notation `.`', () => {
localStorage.setItem('foo', 'bar');
expect(localStorage.foo).toEqual('bar');
});

Input value checked as unique and then added to Object Array - JavaScript

So I'm trying to design a form that will have 3 input fields (Cust ID, Cust Name and Amount), the ID would need to be checked if it exists in the Object Array, and if so throw an error, otherwise it would add all 3 values to the Object Array.
I need to use an object so that I don't use a multitude of Arrays, however I've never actually used an Object based Array, so if anyone is able to provide an example of how to use it that would be a massive help!
var garrCust = {id:"", name:"", amount:""};
function addCust(){
var custID = document.getElementById("custid").value;
var custName = document.getElementById("custname").value;
var amount = document.getElementById("amount").value;
if(!custID){
document.getElementById("output").innerHTML = "ID Cannot be Blank";
return false;}
document.getElementById("output").innerHTML += "<br />Added " + custID + "<br /><br />";
document.getElementById("output").innerHTML += "List contains: " + garrCust.id;
return true;
}
I would use an ID to name-and-amount object map to simplify and speed-up the lookup:
var garrCust = []; // an array of id -> {id:"", name:"", amount:""}
function addCust(){
var custID = document.getElementById("custid").value;
var custName = document.getElementById("custname").value;
var amount = document.getElementById("amount").value;
if(!custID){
document.getElementById("output").innerHTML = "ID Cannot be Blank";
return false;
}
if (!garrCust[custID]) {
// ID not found in the array
garrCust[custID] = { id: custID, name : custName, 'amount' : amount};
document.getElementById("output").innerHTML += "<br />Added " + custID + "<br /><br />";
} else {
document.getElementById("output").innerHTML += "List contains: " + garrCust.id;
}
return true;
}
NOTE: Storing ID as part of object is actually optional as it is already associated with an entry as an array index
You may also use a constructor to define the object content and the id as the property to index them like so:
// Create an object with the two properties name and amount
function Customer(name,amount) {
this.name = name;
this.amount = amount;
}
// Declare some variables
var id, c;
var customers = {};
// Sample names
var name = [ 'one','two','three','four','five' ];
// Create five sample entries - reusing id for amount
for (id = 0; id < 5; id++) {
// Using the new keyword with customer creates the object with
// the data you pass
customers[id] = new Customer(name[id],id);
}
// A loop to test for the presence of customer ids
for (c = 0; c < 5; c++) {
id = Math.floor(Math.random() * 20);
if (customers.hasOwnProperty(id)) {
console.log(id+" exists");
} else {
console.log(id+" does not exist");
}
}
This would create an object that had objects as properties, and the name of the properties is the customer id.
customers = { 44: { name: "John", amount: 6 },
33: { name: "Sally", amount: 5}};
To display the customer list, you may use the following:
var html;
// Use a template literal to build the list item for each customer
function listTemplate(id,name,amount) {
return `<li><span class="id">${id}</span>
<span class="name">${name}</span>
<span class="amount">${amount}</span></li>`;
}
html = "<ul>";
// Iterate through all the customers
for (id in customers) {
c = customers[id];
// Concatenate the list items
html += listTemplate(id,c.name,c.amount);
}
html += "</ul>";
// Add the HTML into the DOM
document.getElementById("customer-list").innerHTML = html;

Javascript OOP issue with variable scope

I'm using an alert() for testing, but I can't get my object to alert the right value of my variables after they have been changed inside of my for loop. I want to store the values in an object using a constructor but only the empty values I set at the beginning are being stored.
//declare the variables I'm going to use inside of my database query and for loop.
$(function(){
var uID = JSON.parse(localStorage.getItem( 'uID' ));
var hood = ' ';
var gender = ' ';
var birthday = ' ';
var zip = ' ';
Parse.initialize("ivHLAO7z9ml1bBglUN*******yCgKM2x","gNeGt04lU7xce*****BsIBSCVj");
$("#mainDiv").on('click', '.interested', function(){
//on click, use "uID" variable to query the parse database to get birthday, gender, neighborhood, and zip
var query = new Parse.Query(Parse.User);
query.equalTo("uID",uID);
query.find({
success: function(results) {
for(i = 0; i < results.length; i++){
//this is where the variable values declared at the beginning are supposed to be changed to the results of the query
hood = results[i].get("neighborhood");
gender = results[i].get("gender");
birthday = results[i].get("birthday");
zip = results[i].get("zipCode");
}
}//closes success
})//closes find
//my object constructor
function interested(neighborhood,sex, bDay, zipCode) {
this.hood = neighborhood;
this.gender = sex;
this.birthday = bDay;
this.zip = zipCode;
}
var intrstd = new interested(hood, gender, birthday,zip);
alert(intrstd.hood);
alert(intrstd.gender);
alert(intrstd.birthday);
alert(intrstd.zip);
});//closes on
If you query is asynchronous, then object is constructed before those variables change. Move your alert into correct scope:
//declare the variables I'm going to use inside of my database query and for loop.
$(function () {
var uID = JSON.parse(localStorage.getItem('uID'));
var hood = ' ';
var gender = ' ';
var birthday = ' ';
var zip = ' ';
Parse.initialize("ivHLAO7z9ml1bBglUN*******yCgKM2x", "gNeGt04lU7xce*****BsIBSCVj");
$("#mainDiv").on('click', '.interested', function () {
//on click, use "uID" variable to query the parse database to get birthday, gender, neighborhood, and zip
var query = new Parse.Query(Parse.User);
query.equalTo("uID", uID);
//my object constructor
function interested(neighborhood, sex, bDay, zipCode) {
this.hood = neighborhood;
this.gender = sex;
this.birthday = bDay;
this.zip = zipCode;
}
query.find({
success: function (results) {
for (i = 0; i < results.length; i++) {
//this is where the variable values declared at the beginning are supposed to be changed to the results of the query
hood = results[i].get("neighborhood");
gender = results[i].get("gender");
birthday = results[i].get("birthday");
zip = results[i].get("zipCode");
}
var intrstd = new interested(hood, gender, birthday, zip);
alert(intrstd.hood);
alert(intrstd.gender);
alert(intrstd.birthday);
alert(intrstd.zip);
} //closes success
}) //closes find
}); //closes on
});

trouble with a search function

function Todo(id, task, who, dueDate) {
this.id = id;
this.task = task;
this.who = who;
this.dueDate = dueDate;
this.done = false;
}
// more code that adds the todo objects to the page and to the array todos
function search() {
for (var i = 0; i < todos.length; i++) {
var todoObj = todos[i];
console.log(todoObj.who); //shows both jane and scott
console.log(todoObj.task); // shows both do something and get milk
}
var searchTerm = document.getElementById("search").value;
searchTerm = searchTerm.trim();
var re = new RegExp(searchTerm, "ig");
var results = todoObj.who.match(re);
if (searchTerm == null || searchTerm == "") {
alert("Please enter a string to search for");
return;
} else {
alert(results);
}
}
This is a search function where I am trying to match what the user types into the search bar with objects that I have created earlier in the code. They must match the "who" and "task" parameters that I have given to the objects. So one object is who: jane task: do something and the other is who: scott task: get milk. The problem is, in my last alert I can only match scott and not jane. Scott is the last one I added. Is there some way I need to modify my loop or change my search criteria?
Your problem is that you are looping through the items, but then using todoObj after that loop. So todoObj will just hold the last item in the array. You need to reorganize a little...try something like this:
function search() {
var searchTerm = document.getElementById("search").value;
searchTerm = searchTerm.trim();
if (searchTerm == null || searchTerm == "") {
alert("Please enter a string to search for");
return;
} else {
var todoObj = undefined,
results = undefined,
re = new RegExp(searchTerm, "ig");
for (var i = 0; i < todos.length; i++) {
todoObj = todos[i];
results = todoObj.who.match(re);
if (results) {
alert("You found " + todoObj.who + ", who needs to " + todoObj.task + " by " + todoObj.dueDate);
return;
}
console.log(re.lastIndex);
}
alert("You didn't match anyone");
}
}
Here's an example of it working as I think you want it to: http://jsfiddle.net/sHSdK/2/

Categories