how to make a new div with jquery? - javascript

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>

Related

How to remove an object from an array if it has the letter a?

I need to make a function that receives 2 parameters, the first one is an array of a list of users that must contain first name, last name and phone numbers, at least 3 of those users must start with the letter "a", the second parameter is a callback. You must process the array and delete all the users whose name starts with the letter "a". Then send the new processed array to the callback. The callback must show in console, the list of all the names, concatenating first and last name.
const users =
[{
name: 'Diego',
lastname: 'Garcia',
phone: '12343'
},
{
name: 'Camilo',
lastname: 'Garcia',
phone: '12343'
}, {
name: 'ana',
lastname: 'Rodriguez',
phone: '02343'
}, {
name: 'anastasia',
lastname: 'Zapata',
phone: '42343'
}, {
name: 'alejandra',
lastname: 'Perez',
phone: '52343'
}];
const operation2 = (list) => {
let x = [];
let callback = {};
callback = list.find(element => element.name.charAt(0) == 'a');
let l = list.indexOf(callback)
let g = list[l];
console.log(g)
if (callback) {
x = list.splice(l, 1)
} return list
}
console.log(operation2(users))
The code that I made does not work, it is not eliminating all the names that begin with "a", it only eliminates the first object of the array.
Array.find only finds the first match, you should probably filter out the elements you don't want:
const result = list.filter(element => element.name.charAt(0) !== 'a');
const users =
[{
name: 'Diego',
lastname: 'Garcia',
phone: '12343'
},
{
name: 'Camilo',
lastname: 'Garcia',
phone: '12343'
}, {
name: 'ana',
lastname: 'Rodriguez',
phone: '02343'
}, {
name: 'anastasia',
lastname: 'Zapata',
phone: '42343'
}, {
name: 'alejandra',
lastname: 'Perez',
phone: '52343'
}];
function func(list, callback) {
let users = list.filter(u => !u.name.toLowerCase().startsWith('a'));
callback(users)
}
func(users, (users) => {
console.log(users)
})

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
}

how to make multi dimensional array with for loop?

FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i=0 ;i<10;i++){
contacts[i] = [];
for(c=0;c<3;c++){
contacts[i].push(FirstName);
contacts[i].push(LastName);
contacts[i].push(Adress);
}
}
the code gives me the contacts array with 10 arrays and each array has the information repeated 3times
You don't need the second for loop:
FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i = 0; i < 10; i++) {
contacts[i] = [];
contacts[i].push(FirstName);
contacts[i].push(LastName);
contacts[i].push(Adress);
}
Or you can also use this way:
FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i = 0; i < 10; i++) {
contacts[i] = [FirstName, LastName, Adress];
}
I am not sure on the objective but I think you should be using objects to store your information instead of 2D arrays.
(Jsfiddle that show 2d array and array with objects). So instead of
var contacts = [
['John', 'Doe', '100 Main Street'],
['Jane','Smith','101 Main']
];
you would have
var contacts = [
{
first_name: 'John',
last_name: 'Doe',
address: '100 Main Street'
},
{
first_name: 'Jane',
last_name: 'Smith',
address: '101 Main Street'
}
];
Try this. It will push the form name and email onto the contacts
<form onsubmit='formSubmit(event);'>
<label>name</label>
<input id='name' value='John'/>
<label>email</label>
<input id='email' value='fake#test.com'/>
<br/>
<button>
add name and email
</button>
</form>
function formSubmit(event){
event.preventDefault();
contacts.push({
name: document.getElementById('name').value,
email: document.getElementById('email').value
})
console.log(contacts);
}

Javascript adding date

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>

Clean Method to Normalize Javascript Object Properties

I have an array of javascript objects that represent users, like so:
[
{ userName: "Michael",
city: "Boston"
},
{ userName: "Thomas",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
phone: "444-4444"
}
]
Some of the objects contain some properties but not others. What I need is a clean way to ensure ALL objects get the same properties. If they don't exist, I want them to have an empty string value, like so:
[
{ userName: "Michael",
city: "Boston",
state: "",
phone: ""
},
{ userName: "Thomas",
city: "",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
city: "",
state: "",
phone: "444-4444"
}
]
Update
I should have been a little more specific. I was looking for an option that would handle this situation dynamically, so I don't have to know the properties ahead of time.
For jQuery specific, the $.extend() option is a good one, but will only work if you know ALL the properties ahead of time.
A few have mentioned that this should probably be a server-side task, and while I normally agree with that, there are two reasons I'm not handling this at the server-side:
1) it will be a smaller JSON object if say 900 of 1000 objects only contain 1 of a possible 9 properties.
2) the "empty" properties need to be added to satisfy a JS utility that could be replaced in the future with something that doesn't care if some properties are missing.
Since you are using jQuery you can abuse $.extend
function Person(options){
return $.extend({
userName:"",
city: "",
state:"",
phone: ""
},options);
}
$.map([{}],Person)
update
Heres a way to have dynamic default properties
function mapDefaults(arr){
var defaultProperties = {}
for(var i =0; i < arr.length; i++){
$.each(arr[i],function(key){
defaultProperties[key] = "";
});
}
function Defaulter(obj){
return $.extend({},defaultProperties,obj);
}
return $.map(arr, Defaulter);
}
mapDefaults([{a:"valA"},{b:"valB"}]);
/* produces:
[{a:"valA",b:""},{a:"",b:"valB"}]
*/
Something you might try is creating a coalescing function:
function coalesceValues(val){
switch(val)
case undefined:
case null:
return '';
break;
default:
return val;
break;
}
}
Or if you wanted to forego customization for simplicity:
function coalesceValues(val){
return val || '';
}
And then apply it when assigning variables:
var city = coalesceValues(obj.city);
This way you don't need to do any crazy breakdown to array and loop or anything, you can apply it to whatever you want, and you can also customize the values you want to coalesce.
Just offering an alternative idea.
The way that is easiest to understand is probably to make a function that accepts an object and uses if statements as existence checks, assigning a default value if it doesn't find it.
function normalize(object) {
if(typeof object.userName === 'undefined') {
object.userName = 'Default Value';
}
if(typeof object.city === 'undefined') {
object.city = 'Default Value';
}
if(typeof object.state === 'undefined') {
object.state = 'Default Value';
}
if(typeof object.phone === 'undefined') {
object.phone = 'Default Value';
}
return object;
}
var userArray = [{},{},{}].map(normalize);
We can also go the constructor route and provide default values on object creation.
function User (data) {
this.userName = data.userName || 'Default Value';
this.city = data.city || 'Default Value';
this.state = data.state || 'Default Value';
this.phone = data.phone || 'Default Value';
return this;
}
var userArray = [{},{},{}].map(function(o){
return new User(o);
});
Of course this depends on one specific type of data and won't extend to other properties and isn't very DRY, but as I said, this is probably the easiest to understand from a beginner's standpoint.
var list = [
{ userName: "Michael",
city: "Boston"
},
{ userName: "Thomas",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
phone: "444-4444"
}
];
for(var i = 0; i < list.length; i++){
if(list[i].state === undefined)
list[i].state = "";
if(list[i].phone === undefined)
list[i].phone = "";
};
console.log(list);
http://jsfiddle.net/g5XPk/1/
This should probably be a server-side task, but..
If you know all the possible properties ahead of time, you could do this:
http://jsfiddle.net/BMau9/
var properties = ['userName', 'city', 'state', 'phone'];
var data = [{
userName: "Michael",
city: "Boston"
}, {
userName: "Thomas",
state: "California",
phone: "555-5555"
}, {
userName: "Kathrine",
phone: "444-4444"
}];
for (var i in data) {
for (var j in properties) {
data[i][properties[j]] = data[i][properties[j]] || '';
}
}
Fiddle
This function stores unique object keys in an array and so you can run your array of objects through it and then use one of the other supplied answers to add the keys to the objects if they do not exist:
function uniqueKeys(){
var keys=[];
function getUniqueKeys(){
return keys
}
function addObject(obj){
for (var k in obj){
keys = _.union(keys,[k]);
}
}
return {
addObj: addObject,
getKeys: getUniqueKeys
}
}
Usage:
var objArr = [{ userName: "Michael", city: "Boston" },
{ userName: "Thomas", state: "California", phone: "555-5555"},
{ userName: "Kathrine",phone: "444-4444" }];
var uniq = new uniqueKeys();
_.each(objArr, function(v){
uniq.addObj(v)
});
var keys = uniq.getKeys();
alert(keys);
vanilla js
let A = [
{
userName: "Michael",
city: "Boston",
},
{
userName: "Thomas",
state: "California",
phone: "555-5555",
},
{
userName: "Kathrine",
phone: "444-4444",
},
];
// set-difference
const diff = (a,b) => new Set([...a].filter((x) => !b.has(x)));
// all keys
const K = new Set(arr.map(o => Object.keys(o)).flat());
// add missing keys and default vals
A.forEach((e,i) => diff(K, new Set(Object.keys(e))).forEach(k => A[i][k] = ""));

Categories

Resources