Appending an object to a predefined array - javascript

I'm having trouble adding a new object to an array.
I have this function, addValue(shopItem, subTotal), where shopItem is a string and subTotal is an integer:
function addValue(shopItem, subTotal)
{
document.getElementById("extraSubHeader").innerHTML = "Current Total: " + subTotal + " Gold";
var object = {name: shopItem.name, description: shopItem.description}
alert("Bought " + shopItem.name + " for " + subTotal + " Gold.")
playerItems.push(object);
}
playerItems is an array of objects, by default it contains this:
playerItems = [
{ name: "Sword", description: "An old, rusty sword." }
];
However, when I try to add the new variable object (above), it instead wipes what I've already entered into the array and replaces it with whatever is in object.
EDIT: I've added a console.log(); to show the playerItems object, and it does in fact contain both objects. It must be a problem with how I iterate and display it. Thanks for everyone's help!

Related

How to get inner array in javascript

I'm trying to get all the contents from an array.
This is the function that extracts the data for display via innerHTML:
window.location.href = 'gonative://contacts/getAll?callback=contacts_callback';
function contacts_callback(obj) {
var contactinfo = obj.contacts.map(({givenName}) => givenName) + " " +
obj.contacts.map(({familyName}) => familyName) + " " + " (" +
obj.contacts.map(({organizationName}) => organizationName) + ") " +
obj.contacts.map(({phoneNumbers.phoneNumber}) => phoneNumbers.phoneNumber) + "<br>";
document.getElementById("demo").innerHTML = contactinfo;
}
This is an example of what the input looks like when there are only 2 contacts:
{"success":true,"contacts":[
{
"emailAddresses":[],
"phoneNumbers":
[
{
"label":"unknown",
"phoneNumber":"XXX-XXXXXXX"
}
],
"givenName":"John",
"organizationName":"Apple",
"familyName":"Appleseed",
},
{
"emailAddresses":[],
"phoneNumbers":
[
{
"label":"unknown",
"phoneNumber":"XXX-XXXXXXX"
}
],
"givenName":"John",
"organizationName":"Apple",
"familyName":"Appleseed",
},
]
}
I just want the result to be listed as:
John Appleseed (Apple) XXX-XXXXXXX
John Appleseed (Apple) XXX-XXXXXXX
Two issues:
You are displaying all given names, then all family names, ...etc, each with a separate .map() call. Instead only perform one .map() call on the array and then display the properties for each iterated object.
phoneNumbers.phoneNumber is not a correct reference. phoneNumbers is an array, so you should iterate it.
Also:
Template literals make it maybe a bit easier to build the string
You can use .join("<br>") to glue the lines together with line breaks.
Here is a corrected version:
function contacts_callback(obj) {
var contactinfo = obj.contacts.map(o =>
`${o.givenName} ${o.familyName} (${o.organizationName}) ${
o.phoneNumbers.map(n => n.phoneNumber)
}`)
.join("<br>");
document.getElementById("demo").innerHTML = contactinfo;
}
// Demo
var obj = {"success":true,"contacts":[{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"John","organizationName":"Apple","familyName":"Appleseed",},{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"John","organizationName":"Apple","familyName":"Appleseed",},]};
contacts_callback(obj);
<div id="demo"></div>
It is hard to give an answer since is hard to tell what you can have in your phoneNumbers array and if you will also display one line for each phone number in that array.
I'll do something like this:
function contacts_callback(obj) {
let arrayContacts = [];
// Iterate over all your contacts
obj.contacts.forEach(item => {
// Iterate over each contact's phone numbers
item.phoneNumbers.forEach(phone => {
// Building your string with string interpolation and pushing to result array
// You could also add <br> or other tags needed here
arrayContacts.push(`${item.givenName} ${item.familyName} (${item.organizationName}) ${phone.phoneNumber}`);
});
});
// Return your array, use it in your innerHTNL, etc.
return arrayContacts;
}
If Your obj is called "obj", than:
const result = obj.contacts.map(contact =>{
return `${contact.givenName} ${contact.familyName} (${contact.organizationName}) ${contact.phoneNumbers[0].phoneNumber}`
}
this code will give back an array of informations that U asked, but if user has more than 1 phone number, it will take only first from the list

How do I access A Subscription within a SubscriptionCollection without a loop in Javascript

I have the following code which works:
ctx.load(workflowAssociations);
//below works but loops through all available workflows, it seems sub may contain the array that needs to be accessed
ctx.executeQueryAsync(function (sender, args) {
var subsEnum = workflowAssociations.getEnumerator();
while (subsEnum.moveNext()) {
var sub = subsEnum.get_current();
alert(sub);
console.log('Web: ' + web.get_url() + ', Subscription: ' +
sub.get_name() + ', id: ' + sub.get_id());
var initiationParams = {};
workflowServicesManager.getWorkflowInstanceService().startWorkflowOnListItem(
sub, items.getItemAtIndex(0).get_id(), initiationParams);
ctx.executeQueryAsync(function (sender, args) {
console.log('Workflow started.');
}, errFunc);
}
}, errFunc);
function errFunc(sender, args) {
alert("Error occured! " + args.get_message() +
'\r\nStack trace: ' + args.get_stackTrace());
}
I am trying to simplify this loop and only access one object in the collection without the while loop. I have tried the following:
//var subsEnum = workflowAssociations.getEnumerator();
console.dir(subsEnum);
console.dir(workflowAssociations[2]);
console.log(subsEnum[2]);
var sub = subsEnum.get_current(0);
console.dir(sub);
console.dir(subsEnum);
However, most of these come up undefined. Here is an image of what it looks like when I explore the object using the watch expression ability in chrome.
I dont want to use that $2_0 thing because in migration I assume it may change.
I apologize in advance for any lack of information.
SP.Workflow.WorkflowAssociation class (workflowAssociations in your example) derives from SP.ClientObjectCollection class which in addition to getEnumerator() method contains some additional methods for accessing collection data such as:
getItemAtIndex - gets the element at the specified index of the SP.ClientObjectCollection class.
getData - transforms ClientObjectCollection object to regular JavaScript array
Examples
Enumerate collection
var e = workflowAssociations.getEnumerator();
while(e.moveNext()){
console.log(e.get_current().get_name()); //print Name of current WorkflowAssociation object
}
Get item at the specified index
var item = workflowAssociations.getItemAtIndex(0); //get first item
console.log(item.get_name()); //print Name of WorkflowAssociation object
Convert to array
var items = workflowAssociations.get_data();
console.log(items[0].get_name()); //print Name of first WorkflowAssociation object

Iterating through an array of objects with properties and printing them to the DOM

We're trying to run through a collection of objects with properties (key: value)'s and write it to the dom.
var productContent = {
item1: {
description: "description 1",
price: 1,
URL: "something1.com",
},
item2: {
description: "description 2",
price: 2,
URL: "something2.com",
},
We've tried a few different types of code, such as:
var productInfo;
var insertProduct = document.getElementById("productList");
for (var i in productContent) {
console.log(productContent[i]);
productInfo += productContent[i];
}
insertProduct.innerHTML = productInfo;
Nothing seems to be working. Any thoughts on how to approach this? We've been able to get properties shown in the console but not much else.
Your first codeblock has a syntax error. The productContent object is missing a closing curly brace: }.
You also have a comma after the last property instead of only between properties.
You should use the JS console in your browser's developer tools to debug this.
You have some errors in your script, you can start with following:
var htmlValue = '';
for (var productKey in productContent) {
var product = productContent[productKey];
htmlValue += 'description: ' + product.description + '<br>';
htmlValue += 'price: ' + product.price + '<br>';
htmlValue += 'url: ' + product.URL + '<br><br>';
}
insertProduct.innerHTML = htmlValue;
Errors:
1.
for (var i in productContent) {
This is just a strong suggestion, but you should change i to something meaningful for the context, such as key since you are iterating over object properties. Naming properly your variables will help you spot errors in your code.
2.
productInfo += productContent[i]
This is not the proper way to concatenate object values. First iteration and it will be "undefined[object Object]".
3.
insertProduct.innerHTML = productInfo;
What are you even trying to do here? You can't just put in element an object. You must put as code and formatted the way you want.

how can I make an for-loop work with a variable inside a variable

first of all, HEY!, I've already asked twice here and both got good answuers that helped a lot.
So... I want to my for-loop print on the console log all my variables on commands variable.
I would like to print only BOH, HALO and BOOM HSAKALAKA variables, not their texts: BOH!, HALO!, BOOM SHAKALAKA!.
var commands = {
'BOH': {text: 'BOH!'},
'HALO': {text: 'HALO!'},
'BOOM SHAKALAKA': {text: 'BOOM SHAKALAKA!'},
};
for (number = 0; number < commands.lenght; number++){
console.log(commands[number]);
};
Something like this DEMO ?
var commands = {
'BOH)': {text: 'BOH!'},
'HALO': {text: 'HALO!'},
'BOOM SHAKALAKA': {text: 'BOOM SHAKALAKA!'},
};
for(key in commands){
if(commands.hasOwnProperty(key)){ //get only the properties of the current object and skip inherited properties
console.log("variable - " + key + " " + "value - " + commands[key].text);
}
};
In your example, you are looping through an array that doesn't exist. commands is not an array, it's an object. So, in order to loop through an object we should use its key property.
In our case key is 'BOH)' and the value of that key is commands[key] => BOH!.

Array of objects in Javascript - using "push"

I am very new with Javascript and I can't seem to find an explanation for what is happening with my code.
I want to create an array of "people" where each person has some information associated with them, like "id" and "name". I don't know how many "people" I would need in my array so I am using "push" when I need another person. My problem is my array ends up filled with the last person's information.
Here is my declarations that I am using:
var ppl_arr = [];
var profile = {
id: 10000,
name: " ",
};
profile.id=3;
ppl_arr.push(profile); //add this person to my array
alert(ppl_arr[0].id + "\t" + ppl_arr.length);
profile.id=5;
ppl_arr.push(profile); // push next person to the array
alert(ppl_arr[0].id+"\t"+ppl_arr[1].id + "\t"+ppl_arr.length);
The first alert displays correctly : "3 1"
In the second alert, I get " 5 5 2" instead of " 3 5 2"
So I get two entries into my array but the second one seems to overwrite the first one. Can anyone explain what is happening?
You are simply changing the id of the same object, and adding the same object to the array twice. I would suggest that you create your 'people' objects as instance objects, something like this
//This is a constructor function for a Person object
function Person(id,name)
{
this.Id = id;
this.Name = name;
}
then
var ppl_arr = [];
ppl_arr.push(new Person(3,"Bob")); //add this person to my array
alert(ppl_arr[0].Id + " - " + ppl_arr.length); //outputs "3 - 1"
//NOTE put a string inbetween, because Id and length are both integers,
//you would actual get a sum of the two, not a string concatenation.
ppl_arr.push(new Person(5,"Steve")); // push next person to the array
alert(ppl_arr[0].Id+"\t"+ppl_arr[1].Id + "\t"+ppl_arr.length); // outputs 3 5 2
Question #1:
alert(ppl_arr[0].id + ppl_arr.length); will display the sum, not the concatenation - try alert(ppl_arr[0].id.toString().concat(ppl_arr.length));
Question #2:
You change the id property of an existing object, not copy it. So you change the id of the object already in the array as well. So you would need to
var ppl_arr = [];
var profile = {
id: 10000,
name: " ",
};
profile.id=3;
ppl_arr.push(profile);
//Create a new profile
var profile2 = {
id: 10000,
name: " ",
};
profile2.id=5;
ppl_arr.push(profile2);

Categories