Javascript adding date - javascript

i have been given this code and told to add in the setup method to add the 4 fish owners.
Controller.prototype.setup = function () {
'use strict';
var theAquarium;
theAquarium = new Aquarium();
i have to add the following information
to add for each owner:
PHK Phil Key 8/05/1980
RUT Russel Turia 16/02/1984
TAN Tariana Norman 30/11/1987
JOG John Goff 12/12/1982
i tried adding it like this but it isn't working
Controller.prototype.setup = function () {
'use strict';
var theAquarium;
theAquarium = new Aquarium();
theAquarium.addFishOwner( 'PHK' , 'Phil' , 'Key' , setFullYear(8/05/1980));
theAquarium.addFishOwner( 'RUT' , 'Russel' , 'Turia' , setFullYear(16/02/1984));
theAquarium.addFishOwner( 'TAN' , 'Tariana' , 'Norman' , setFullYear(30/11/1987));
theAquarium.addFishOwner( 'JOG' , 'John' , 'Goff' , setFullYear(12/12/1982));
please help

Try this, let me know if I understand what you are asking
$(document).ready(function() {
var fisherman1 = {
name: "John",
lastName: "Doe",
DOB: '8/05/1980'
};
var fisherman2 = {
name: "John1",
lastName: "Al",
DOB: '8/05/1980'
};
var fisherman3 = {
name: "Alan",
lastName: "123",
DOB: '8/05/1980'
};
var fisherman4 = {
name: "Jim",
lastName: "A",
DOB: '8/05/1980'
};
var array1 = new Array(4);
array1.push(fisherman1);
array1.push(fisherman2);
array1.push(fisherman3);
array1.push(fisherman4);
for (x = 0; x < array1.length; x++) {
$("div").append(x + ":" + array1.pop(0).name + ".");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d"></div>

Related

Compare and get difference from two object for patch api request in react js?

i m having two objects previous and new one, i trying to compare and get difference for those objects, send to as patch payload from patch api,
compare each properties in object if any of the property has any difference i want all those difference in new object as payload
How can i achieve this please help me find the solution?
Is there any lodash method for this solution?
let obj = {
Name: "Ajmal",
age: 25,
email: "ajmaln#gmail.com",
contact: [12345678, 987654321],
address: {
houseName: "ABC",
street: "XYZ",
pin: 67891
}
}
let obj2 = {
Name: "Ajmal",
age: 25,
email: "something#gmail.com",
contact: [12345678, 11111111],
address: {
houseName: "ABC",
street: "XYZ",
pin: 111
}
}
result payload i m expecting would look like
let payload = {
email: "something#gmail.com",
contact: [12345678, 11111111],
address: {
pin: 111
}
}
Mista NewbeedRecursion to your service:
const compare = (obj1, obj2) => {
const keys = Object.keys(obj1);
const payload = {};
keys.forEach((el) => {
const first = obj1[el];
const second = obj2[el];
let check;
if (first !== second) {
if (first instanceof Object && !(first instanceof Array))
check = compare(first, second);
payload[el] = check || second;
}
});
return payload;
};
Here is a approach with immer that may guide you to a proper solution
This is not a generic approach but makes things easier by relying on immer
import produce, { applyPatches, enablePatches } from "immer";
import { difference } from "lodash";
// once in your app
enablePatches();
let obj = {
Name: "Ajmal",
age: 25,
email: "ajmaln#gmail.com",
contact: [12345678, 987654321],
address: {
houseName: "ABC",
street: "XYZ",
pin: 67891
}
};
let obj2 = {
Name: "Ajmal",
age: 25,
email: "something#gmail.com",
contact: [12345678, 11111111],
address: {
houseName: "ABC",
street: "XYZ",
pin: 111
}
};
Gettig the patch updates
let fork = { ...obj };
let changes = [];
const updatedItem = produce(
fork,
(draft) => {
// object specific updates
draft.Name = obj2.Name;
draft.age = obj2.age;
draft.email = obj2.email;
draft.address.houseName = obj2.address.houseName;
draft.address.street = obj2.address.street;
draft.address.pin = obj2.address.pin;
const originalContact = original(draft.contact);
const contactDiff = difference(obj2.contact, originalContact);
console.log("diff", contactDiff);
if (contactDiff?.length) {
draft.contact = contactDiff;
}
},
(patches) => {
changes.push(...patches);
}
);
//Problem here => default values need to be given to state
// so the default values need to be excluded from the patch
let state = { contact: [], address: {} };
const patch = applyPatches(state, changes);
console.log("patch", patch);
logs changes op
contact: Array(1)
0: 11111111
address: Object
pin: 111
email: "something#gmail.com"
Hope this helps you in some way
Cheers

how to make a new div with jquery?

okay so, I need to create a new div using jquery with the information of a first and last name that I loop from my array.. This is what I have so far, I was wondering if I could get some help on how to make it show up on my webpage. it needs to show up like:
hello firstname lastname
hello firstname lastname
hello firstname lastname
<div id="output"></div>
function names() {
var firstAndLast = [
{name: "jane", surname: "doe"},
{name: "john", surname: "leg"},
{name: "hunny", surname: "bun"}
];
var div = $("#output");
for (var i=0; i < firstAndLast.length; i++) {
}
var div1 = $("<div>").html("Hello name surname");
$("#names").append(div1);
Your code is almost there. The main issue is that you need to put the line of jQuery which creates the div and appends it within the for loop. In addition you can retrieve the name and surname from the objects in the array using the i variable to access them by index:
var $output = $("#output");
for (var i = 0; i < firstAndLast.length; i++) {
var div1 = $("<div>").html(`Hello ${firstAndLast[i].name} ${firstAndLast[i].surname}`);
$output.append(div1);
}
That being said, the most performant way to do this would be to use map() to build an array of HTML strings which you only append to the DOM once:
function names() {
let firstAndLast = [
{ name: "jane", surname: "doe" },
{ name: "john", surname: "leg" },
{ name: "hunny", surname: "bun" }
];
let html = firstAndLast.map(o => `<div>Hello ${o.name} ${o.surname}</div>`);
$("#output").append(html);
}
names();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output"></div>
You can try something like this
function names() {
var firstAndLast = [{
name: "jane",
surname: "doe"
},
{
name: "john",
surname: "leg"
},
{
name: "hunny",
surname: "bun"
}
];
let _data = firstAndLast.reduce((acc, {
name,
surname
}) => {
acc += `hello <span>${name}</span> <span>${surname}</span><br>`
return acc;
}, "")
$("#output").html(_data);
}
names()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">
</div>

Want to achieve functionality by using Javascripts map,reduce,foreach,filter methods

Please help me to write better code.
Suppose I have a JavaScript array like below:
var students = [
{ firstname: "stud1", lastname: "stud2", marks: "60" },
{ firstname: "stud3", lastname: "stud4", marks: "30" },
{ firstname: "stud5", lastname: "stud6", marks: "70" },
{ firstname: "stud7", lastname: "stud8", marks: "55" },
{ firstname: "stud9", lastname: "stud10", marks: "20" },
];
On page I want to show data in two parts, 1)Students who got marks >= 40 2)Students who got marks < 40
By using for loop I done this functionality easily as below.
var data = "";var data1 = "";
for (var i = 0; i < students.length; i++ )
{
if(students.marks >= 40){
data += = students.firstname + " " + students.lastname; //actual data in html div tag
....
}else{
data1 += = students.firstname + " " + students.lastname;
}
}
I want to achieve same functionality by using JavaScript methods like map, reduce, foreach, filter etc. (want to improve my JavaScript knowledge)
Don't know exactly which method is useful for such functionality.
Used map method and tried to display data, but there is a trailing , at the end of each object/array.
Can anyone please help/guide me to write proper code?
Here is solution using filter and forEach methods, using callback functions.
See references here :
filter method
var students = [
{ firstname: "stud1", lastname: "stud2", marks: "60" },
{ firstname: "stud3", lastname: "stud4", marks: "30" },
{ firstname: "stud5", lastname: "stud6", marks: "70" },
{ firstname: "stud7", lastname: "stud8", marks: "55" },
{ firstname: "stud9", lastname: "stud10", marks: "20" },
];
students.filter(function(item){
return item.marks>=40;
}).forEach(function(item){
div=document.getElementById('persons');
div.innerHTML+=item.firstname+' '+item.lastname+'<br>';
});
<div id="persons"></div>
You could use a single loop and add the information with predicate as index. Later join the elements for getting a sting for each element.
var students = [{ firstname: "stud1", lastname: "stud2", marks: "60" }, { firstname: "stud3", lastname: "stud4", marks: "30" }, { firstname: "stud5", lastname: "stud6", marks: "70" }, { firstname: "stud7", lastname: "stud8", marks: "55" }, { firstname: "stud9", lastname: "stud10", marks: "20" }],
predicate = function (o) { return o.marks >= 40; },
result = [[], []];
students.forEach(function (a) {
result[+predicate(a)].push(a.firstname + ' ' + a.lastname);
});
result = result.map(function (a) { return a.join(', '); });
console.log(result);

JavaScript build a dynamic object

I have a var named onversation that contains this:
{
"conversationId": "adbabc54-3308-436d-a48b-932f4010d3c6",
"participantId": "415651e6-f0a5-4203-8019-4f88c3ed9cd5"
}
I also have an object named person that contains this:
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
What I'd like is to have a combined object called result that looks like this
result {
conversation {
conversationId : adbabc54-3308-436d-a48b-932f4010d3c6,
participantId : 415651e6-f0a5-4203-8019-4f88c3ed9cd5
},
person {
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
}
How would I do this dynamically whereby the result object is built using the name of the var 'conversation' and name of the object 'person' ?
Also, the length of either conversation or person can be any length.
Pure JavaScript if possible , but could use underscore etc.
Try it
var result = {
'conversation': conversation,
'person': person
}
Dynamic
var result = {}
result['person'] = person
or
resilt.person = person
If I understand your question correctly, you can use object shorthand notation which is supported in most browsers (Probably all of them, except IE11) for simplifying your solution even more:
var conversation =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var person =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = { conversation, person }
console.log(result)
EDIT:
If only the variable name changes, and it's properties names stay the same or have some sort of unique key, you can use a for loop on the object's keys.
For example:
var someConversationVariableName =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var somePersonVariableName =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = { someConversationVariableName, somePersonVariableName }
for (key in result) {
if(result[key]['conversationId']) {
console.log(`Found conversation object. It's name is: ${key}`);
}
else if(result[key]['firstname']) {
console.log(`Found person object. It's name is: ${key}`);
}
}
If you need to defer adding objects, you can also take this approach:
var conversation =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var person =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = {};
result['conversation'] = conversation;
result['person'] = person;
console.log(result);
This Must work :-
var conversation =
{
"conversationId": "adbabc54-3308-436d-a48b-932f4010d3c6",
"participantId": "415651e6-f0a5-4203-8019-4f88c3ed9cd5"
}
var person=
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
var result = {
'conversation': conversation,
'person': person
}

IndexedBD select objects from upper to lower?

For example:
const customerData = [
{ id: 444, name: "Bill", age: 35, email: "bill#company.com" },
{ id: 5555, name: "Donna", age: 32, email: "donna#home.org" },
{ id: 666, name: "Cat", age: 2, email: "cat#home.org" },
{ id: 888, name: "Gandalf", age: 21000, email: "gandalf#home.org" }
];
function getDataByRange(db, table, index, lower, upper, fun){
var data = [];
var tx = db.transaction(table, "readonly");
var store = tx.objectStore(table);
var index = store.index(index);
var boundKeyRange = IDBKeyRange.bound(lower, upper, false, false);
var request = index.openCursor(boundKeyRange);
request.onsuccess = function() {
var cursor = request.result;
if (cursor) {
data.push(cursor.value);
cursor.continue();
} else {
fun(data);
}
};
}
How to get next results: Gandalf, Bill, Donna, Cat?
Now I get something like: Cat,Donna, Bill, Gandalf.
Thanks for any suggestions!
The openCursor method accepts two arguments. The second argument is optional and specifies the direction of the cursor. Because it is optional, you rarely see the second argument specified in example code, so maybe that is why it is confusing.
There are four possible direction values: next, prev, nextUnique, and prevUnique. You specify the argument as a string. next is the implied default argument.
So, use openCursor(boundKeyRange, 'prev') to iterate in reverse.

Categories

Resources