Update 'nested' javascript object dynamically - javascript

I'm trying to create an object that is updated dynamically.
Here's the setup of the type of object I'd like to create (note: I may add other things, such as address, country, etc to the keys):
var contacts = {"Bruce Wayne":{"phone number":'123-456-7890', "email":"bwayne#night.com"}, "Alfred":{"phone number" :'987-654-3210', "email": "alfred#yourang.com"}, "Clark Kent":{"phone number":'951-753-8520', "email":"nothing#krypton.com"}}
So for each name (Bruce Wayne, Alfred, ...) I have some keys assigned to them.
I'm using npm faker to generate some fake data to try and populate an array like the above, with the outline
I'm able to get a loop going, but it always returns the last iteration's data. I understand it's because I'm doing contact = .... Since this is an object, I can't use push, AFAIK.
function getContact(numContacts){
contacts = {}
for (var i = 0; i < numContacts; i++){
console.log(i);
var name = faker.name.firstName() + " " + faker.name.lastName();
var phoneNum = faker.phone.phoneNumber();
var email = faker.internet.email();
contacts = {name :{ "phone number": phoneNum, "email": email}}
// contacts.name = {"phone number": phoneNum, "email":email}; // this also returns just the last instance.
};
return contacts;
};
var contacts = getContact(10); // This should create ten people, each with a phone number and email.
The loop almost successfully creates a single name. This returns:
name, 761.704.3328 x4287, Leopold81#hotmail.com
But in that iteration, name variable is actually Joe Schmoe, not literally name...
What am I overlooking to make sure that the contacts object gets populated with 10 people, with the resolved name, not just the last in the iteration?

Observations
You're trying to use name variable as key, however, what you're doing is adding a key literally called name.
What you have to do, is to create the key programmatically as follow: contacts[name] and assign the object with phoneNumber and Email.
This code is an example to simulate your scenario.
var faker = {
name: {
firstName: function() {
return "Clark";
},
lastName: function() {
return "Kent";
}
},
phone: {
phoneNumber: function() {
return '951-753-8520';
}
},
internet: {
"email": function() {
return "nothing#krypton.com";
}
}
};
function getContact(numContacts) {
var contacts = {}
for (var i = 0; i < numContacts; i++) {
var name = faker.name.firstName() + " " + faker.name.lastName();
var phoneNum = faker.phone.phoneNumber();
var email = faker.internet.email();
contacts[name + '_' + i] = {
"phone number": phoneNum,
"email": email
}
}
return contacts;
}
var contacts = getContact(10);
console.log(contacts);

The names are the keys in your object. You can use it like an array index to populate contacts. This should work:
contacts[name] = {"phone number": phoneNum, "email": email}

Related

How to create a list of contacts using javascript?

I've got to create a list of contacts using javascript which allows the user to enter contacts, and so that the program runs until the user quits. I'm a little lost as to whether I need to add alerts or not. Here's some of my code below, it's a work in progress so there are no expected console outcomes from it as yet.
/*
Activity: Contact manager
*/
// TODO: Complete the program
var Contact = {
// initialise contacts
init: function(last_name, first_name) {
this.last_name = last_name;
this.first_name = first_name;
},
describe: function () {
var description = this.last_name + "," + this.first_name;
return description
},
// add a contact
contact_list: function () {
var list_of_contacts = []
}
}
var contact1 = Object.create(Contact);
contact1.init("Smith", "John");
var contact2 = Object.create(Contact);
contact2.init("Doe", "Jane");
var contact_list = [];
contact_list.push(contact1);
contact_list.push(contact2);
This is what the console should look like, if the exercise is completed successfully:
Welcome to your contacts manager!
1: List contacts
2: Add a contact
0: Quit
Upon providing the option 1:
Here's the list of all your contacts:
Last name: Smith, first name: John
The rest is almost identical.
You already have a list, you are pusing them to the array: contact_list.push(contact1);
In order to log output a list, all you have to do is loop the array and print each name;
let output = "contacts: ";
for(let i=0;i< contact_list.length; i++){
output+= "Last name:" + contact_list[i].last_name + ", first name:" +contact_list[i].first_name ;
}
console.log(output);

Iterating over a json array whose key value is dynamic

I have a json structure as:
{
"TestCaseList": [
{
"TC_1": {
"name":"verifyloginpagedetails",
"value":"2"
},
"TC_2": {
"name":"verify registration page details",
"value":"3"
}
}
],
"Summary": {
"v":[
{
"name":"over the ear headphones - white/purple",
"value":1
}
]
}
}
How to extract the values name, value of TC_1 , TC_2 where TC_1 is dynamic i.e. key of TestCaseList?
You can use the Object.keys method to get an array of the keys of an object.
With a single object in the array at "TestCaseList" in your JSON object, this will work:
// jsonObj is your JSON
testCaseKeys = Object.keys(jsonObj.TestCaseList[0]);
If, however, the array at "TestCaseList" contains more than one one element, you can use this to get each set of keys in an individual array:
testCaseKeySets = jsonObj.TestCaseList.map(obj => Object.keys(obj));
I'm sure a more elegant solution exists, but this will do the trick.
var myObj = {
"TestCaseList":
[{
"TC_1":
{"name":"verifyloginpagedetails",
"value":"2"},
"TC_2":
{"name":"verify registration page details",
"value":"3"}
}],
"Summary":{
"v":[{"name":"over the ear headphones - white/purple","value":1}]
}
}
let testCaseListKeys = Object.keys(myObj.TestCaseList[0]);
for(i=0; i < testCaseListKeys.length; i++){
let tclKey = testCaseListKeys[i];
console.log(tclKey + "\'s name = " + myObj.TestCaseList[0][tclKey].name);
console.log(tclKey + "\'s value = " + myObj.TestCaseList[0][tclKey].value);
}
The console.logs are your output. The important values there are the myObj.TestCaseList[0][tclKey].name and the myObj.TestCaseList[0][tclKey].value
** UPDATE **
After answering the question Ananya asked how to do this same thing if the object had a different structure.
Updated Object:
var myObj2 = {
"TestCaseList":
[{
"TC_1":{
"name":"verifyloginpagedetails",
"value":"2"}
},
{
"TC_2":{
"name":"verify registration page details",
"value":"3" }
}],
"Summary":
{
"v":[ {"name":"over the ear headphones - white/purple","value":1} ]
}
}
Updated JavaScript:
for(x=0;x<myObj2.TestCaseList.length;x++) {
let testCaseListKeys = Object.keys(myObj2.TestCaseList[x]);
for(i=0; i < testCaseListKeys.length; i++){
let tclKey = testCaseListKeys[i];
//console.log(tclKey);
console.log(tclKey + "\'s name = " + myObj2.TestCaseList[x][tclKey].name);
console.log(tclKey + "\'s value = " + myObj2.TestCaseList[x][tclKey].value);
}
}

How to dynamically add users on the page using jquery

Im having some trouble figuring this out. I have a database which has users on it and I want to display each user on the page dynamically using jquery.
Ive just thrown some user data objects in a array and im trying to call for each user object in the array to display as a list item on the page
html
<h1>List</h1>
<ul id="list">
</ul>
javascript
var user = [
{
username: alex,
age: 20
},
{
username: james,
age: 20
}
]
function addUser() {
var username = user.username;
var age = user.age
var $user = $("<li>" + username + "</li>");
var $age = $("<li>" + age + "</li>");
$("#list").append($user + " " + $age);
}
$.each(user, addUser());
Your mistake is very simple. You have to replace addUser() by addUser when you use the $.each method. There are also mistakes when you use the.append method. Try this code:
var user = [
{
username: "alex",
age: 20
},
{
username: "james",
age: 20
}
];
function addUser(theCase, value) {
var username = value.username;
var age = value.age;
var user = '<li> ' + username; // Use a simple string, it's better and faster!
var age = age + ' </li>';
$("#list").append(user + " " + age);
}
$.each(user, addUser);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<h1>List</h1>
<ul id="list">
</ul>
Here you are using a callback. If you want more details about callbacks consult the MDN's documentation.
There are also several errors on .each method or .append method. Consult the documentation.
The .each method call your callback for each case on your array user. This method also provide you, in your callback, the index and the value of the case witch is treated.
Can you please check page: https://jsfiddle.net/rxcz73x9/2/
var user = [{
username: "alex", // use string
age: 20
}, {
username: "james", // use string
age: 20
}];
function addUser(idx, user) {
var username = user.username;
var age = user.age
var $user = $("<li>" + username + "</li>");
var $age = $("<li>" + age + "</li>");
$("#list").append($user).append($age); // use append for each node
}
$.each(user, addUser); // use function name instead of addUser()
I've added comment that could help you with example above.
When you pass a callback to the jQuery each function, what happens is that the callback is going to be invoked with every element in your user array.
Check the arguments that jQuery.each passes to the callback. The callback function signature should expect the index and the value of the element in that index.
For example:
var users = user = [
{
username: alex,
age: 20
},
{
username: james,
age: 20
}
];
function addUser(index, user) {
// do what you want and in the end
$('#list').append(/* an <li> element */);
};
// Now pass the function as a callback, but don't invoke it.
$.each(users, addUser);

function to save JS object not working

I made a HTML project called Customer with some text boxes where can I enter some text and a button called save.Now I want to create a function in JavaScript to save a new contact object.
I tried this:
function SaveContact() {
var list = [];
var firstName = document.getElementById("first_name");
var lastName = document.getElementById("last_name");
var phoneN = document.getElementById("phone");
var emailN = document.getElementById("email");
var birthDay = document.getElementById("birth_day");
var birthMonth = document.getElementById("birth_month");
var birthYear = document.getElementById("birth_year");
list.push({ firstName, lastName, phoneN, emailN, birthDay, birthMonth, birthYear });
return list;
But it doesn't change anything. Where am I wrong?
The problem with the following line:
list.push({ firstName, lastName, phoneN, emailN, birthDay, birthMonth, birthYear });
is that you're only saving values. In JS, you need both values and keys. Therefore, you would need to change it to:
list.push({ "firstName": firstName, "lastName": lastName, "phoneN": phoneN, "emailN": emailN, "birthDay": birthDay, "birthMonth":birthMonth, "birthYear":birthYear });
EDIT
You say you want to create an object but you want to store them as an array. To store them as an array (an object with keys as their indeces), just remove the { and } in the push() line.
However, I think it would be easier to just create an object, like so:
function SaveContact() {
return {
"firstName": document.getElementById("first_name"),
"lastName": document.getElementById("last_name"),
"phoneN": document.getElementById("phone"),
"emailN": document.getElementById("email"),
"birthDay": document.getElementById("birth_day"),
"birthMonth": document.getElementById("birth_month"),
"birthYear": document.getElementById("birth_year")
};
}
This one-statement function simply creates and returns an object literal, rather than assigning the values to variables and then putting them into an array/object.
But if you really do want an array, just replace the { and } with [ and ] and remove the keys. This will get you the output you are currently trying to achieve with your program.
Push does not need the { ... } around the elements:
array.push(item1, item2, ..., itemX)
(from here)
Also, note that you are storing DOM Elements in the the list. You probably need their values and not the elements but it depends on what you try to do...
EDIT - after seeing Jonathan's answer
Alternatively you can do:
obj = {}
obj.name = document.getElementById("first_name")
// ... more fields
list.push(obj)

I don't understand this function. [Codecademy Contact List excercise]

So the "for var x in friends" loop is going to search each key inside friends, which would be bill and steve, and then with "friends[x].firstName === name" we are checking if the first name is equal to "name", but how does the program know if "name" is Steve or Bill? I'm missing something here.
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: " ",
address: [' ', ' ', ' ',' ']
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: " ",
address: [' ', ' ', ' ',' ']
}
};
var list = function(friends) {
for (var x in friends) {
console.log(x);
}
};
var search = function(name) {
for (var x in friends) {
if(friends[x].firstName === name) {
console.log(friends[x]);
return friends[x];
}
}
};
for (var x in friends)
This iteates over all keys in friends, resulting in two loop iterations with
x = "bill"
x = "steve"
Then with friends[x] in the loop you access friends.bill and freinds.steve.
The name variable is given as a parameter to search(name). This effectivly searches all entries in the dict friends for firstName == name.
here we have defined search as a function search which accepts an argument name .
var search = function(name)
and we use the function like
search('Bill')
So the function knows which name we are looking for, which is Bill . It will iterate through each item and compare each firstName with Bill. It returns the corresponding friends[x] , when it finds a match .
The advantage of function with parameter is that, with the same function we can search for any name . ex : search('Steve') , search('Bill') .
if you don't understand functions with parameters, revisit the codeacademy section understanding parameters - js

Categories