Push a var in an array - javascript

Im fairly new to programming. Mostly I can find the solution to my problems online but not this time. I've found serveral posts about pushing a variable into an array, however when I console.log the array to check if the variable is actually in the array, he doesn't return the name of the variable that I want. What I get back is: [Card, Card], and what I want to see is: [card_Fireball, card_Waterbolt, etc]. The code I use is:
var Deck = [];
function Card(name, type, cost, points, damage, heal){
this.name = name;
this.type = type;
this.cost = cost;
this.points = points;
this.damage = damage;
this.heal = heal;
}
var card_Fireball = new Card("Fireball", "spell", 2, 1, 3, 0);
var card_Waterbolt = new Card("Waterbolt", "spell", 2, 1, 3, 0);
Deck.push(card_Fireball);
Deck.push(card_Waterbolt);
console.log(Deck);
The solution is probably fairly simple but I can't figure it out with my beginner experience :P Thanks for the help!!

You are doing everything correct just replace console.log with following:
console.log(JSON.stringify(Deck));

Access the card names with "Deck[x].name", where x is the index of the card in the array Deck.
To get all the names:
for(i=0;i<Deck.length;i++){
console.log(Deck[i].name);
}
Assuming you name all your cards the same way as you did in your example, you could use this to get the variable names:
for(i=0;i<Deck.length;i++){
console.log('card_' + Deck[i].name);
}

If you want to get an array of the variable names you have used, those are lost on the way.
In case you want an array of the names or any other property, try making a new array and pushing every value to it.
var names = [];
Deck.map(function(v) { names.push(v.name) })
console.log(names);
Output:
["Fireball", "Waterbolt"]

Related

How to access object with a randomly chosen name stored in a variable?

I've got 16 objects with names like: aBoard, bBoard, cBoard and so on,
eg. let aBoard = { currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true };
I have an array of corresponding names, randomly chose one of them and change it so it matches the name of one of the objects.
const BOARDARRAY = ["unitA", "unitB", "unitC", "unitD", "unitE", "unitF", "unitG", "unitH", "unitI", "unitJ", "unitK", "unitL", "unitM", "unitN", "unitO", "unitP"];
let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];
let temp = (currentBoardTile.charAt(currentBoardTile.length -1).toLowerCase());
JSObjectBoardUnit = (temp + "Board");
How to access the object using my JSObjectBoardUnit?
In other words, how to make JS "understand" that I want to treat JSObjectBoardUnit value (string) as a value of the object address?
Eg. Let's day JSObjectBoardUnit = aBoard;
Basically the outcome I want is: aBoard.key1 = JSObjectBoardUnit.key1.
I'd love to use the value stored in JSObjectBoardUnit to access the name of the predefined object aBoard.
I'm not sure to understand well your question but I think this 2 methode could maybe help you.
You can access attribute of a object with a string by using
const obj = {toto: 1};
const name = "toto";
console.log(obj["toto"]); // 1
console.log(obj[name]); // here we use variable and the result is 1
so you could store all yoyr object inside one and do this.
const allBoard = {
"aboard": null, // do not put null use your board
}
console.log(allBoard[(temp + "board")]); // display the temp + board attribute so if temps is equal to a then it will get the aboard
this is what you want, getting object from a string.
But I saw that the aboard also have an id attribute with "unitA"
Instead you could build an array of aboard, bboard ....
and use the Array.find() methode that will return the object that match the condition.
in your case
const myBoardArray = [{ currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true }, ....];
let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];
myBoardArray.find((board) => board.ID === currentBoardTile);
2 options
Put the boards in a list, and iterate over them with a for loop. In the for loop, use an if statement to see which Id matches the board you want.
let boards = [aBoard , bBoard, cBoard];
boards.forEach(board=> {
if (board.ID == currentBoardTile) {
//do something
}
});
Create a dictionary where the key is the board id and the respective object is the value. Use the board id to get the respective value.
var boards = {
"unitA" : boardA,
"unitB" : boardB,
....
};
currentBoardTile = BOARDARRAY[randomizer];
console.log(currentBoardTile + " : " + boards[currentBoardTile]);

Find a string within a jQuery array that has multiple elements per object

I've got an array of employee's and assigned to each employee are a few elements.
Sample of array below:
var employees = [
{"name":"Johhny Test","salary":"1","email":"abc#123.com"},
{"name":"Mike Milbury","salary":"10","email":"184895#hdsjhfs.com"}
];
I've got a means of gathering the employee's last name and I'm storing it in a variable. I'd like to be able to search for the indexOf the last name housed in this variable so that I know at which position within the array that match is made.
So for instance, this array could be 100 items in size. Ideally I want to know that someone with the last name of "johnson" is in position 50 of this array. That way, I can go in and get the salary and email associated with their record from position 50 in the array.
The code I've got so far is this:
var lname = "Test";
var lnameMatch = employees.indexOf(lname);
console.log(lnameMatch);
This isn't working though - my console is logging -1, suggesting that it doesn't exist in the array. Is there a way that I can specify a element of that array to search against?
Almost like employees(name).indexOf(lname) where it is searching against the name element?
Or am I going about this all wrong and there is perhaps an easier less messy way to accomplish this?
You can use .findIndex:
const employees = [
{"name":"Johhny Test","salary":"1","email":"abc#123.com"},
{"name":"Mike Milbury","salary":"10","email":"184895#hdsjhfs.com"}
];
const lastName = "Test";
const index = employees.findIndex(employee => {
const { name = '' } = employee;
const nameParts = name.split(' ');
const lname = nameParts[nameParts.length-1];
return lastName === lname;
});
console.log(index);
console.log(employees[index]);

How to append data to an object with Javascript

Heres is how I add data to my object:
let trade = [
new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol),
]
The problem is when I run this:
console.log(trade[0].price);
It seems that overwrites my object from the beginning.
I add my class code. How i can print the first data from the object
class RecordStock {
constructor(price, timestamp, stockquantity, tradetype, stocksymbol) {
this.price = price;
this.timestamp = timestamp;
this.stockquantity = stockquantity;
this.tradetype = tradetype;
this.stocksymbol = stocksymbol;
}
static recordTrade(){
console.log(price[0]);
}
}
I think you are looking to push objects into the trade array. You can achieve this by simply appending to the array.
You can push objects with something like this
Assuming you have a function that adds the RecordStock object. Here is how it could be.
let trade = [];
trade.push(new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol));
trade.push(new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol));
trade.push(new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol));
Now you can access the latest RecordStock you pushed using this trade[trade.length - 1]. trade[0] will always contain the object which you pushed first. This is the usual array functionality.
The problem is that inside the function I declare de var every time. I put let trade out of the function

How to convert arrays to objects in javascript?

How could I rewrite this code to object javascript. Since Array usage is prohibed, I can only use objects here. Insted of pushing values to array, I would like to push this values into objects.
var container = [];
document.addEventListener("submit", function(e){
e.preventDefault();
});
window.addEventListener("load",function(){
var submit = document.getElementsByClassName("btn-primary");
submit[0].addEventListener("click",add,false);
document.getElementById("pobrisi").addEventListener("click",deleteAll,false);
var dateElement = document.getElementById('datum');
dateElement.valueAsDate = new Date();
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
today = yyyy+'-'+mm+'-'+dd;
dateElement.setAttribute("min",today);
});
function add() {
var title = document.getElementById("title").value;
var type = document.getElementById("type").value;
var datum = document.getElementById("datum").value.split("-");
datum = datum[2]+". "+datum[1]+". "+datum[0];
var data = new Book(title,type,datum);
container.push(data.add());
display();
}
function display(data) {
var destination = document.getElementById("list");
var html = "";
for(var i =0;i <container.length; i++) {
html +="<li>"+container[i]+"</li>";
}
destination.innerHTML = html;
}
function deleteAll(){
container=[];
document.getElementById("list").innerHTML="";
}
Wondering if is possible to write this code whitout any array usage.
initial remarks
The problem here, in my estimation, is that you haven't learned the fundamentals of data abstraction yet. If you don't know how to implement an array, you probably shouldn't be depending on one quite yet. Objects and Arrays are so widespread because they're so commonly useful. However, if you don't know what a specific data type is affording you (ie, what convenience does it provide?), then it's probable you will be misusing the type
If you take the code here but techniques like this weren't covered in your class, it will be obvious that you received help from an outside source. Assuming the teacher has a curriculum organized in a sane fashion, you should be able to solve problems based on the material you've already covered.
Based on your code, it's evident you really have tried much, but why do you think that people here will come up with an answer that your teacher will accept? How are we supposed to know what you can use?
a fun exercise nonetheless
OK, so (we think) we need an Array, but let's pretend Arrays don't exist. If we could get this code working below, we might not exactly have an Array, but we'd have something that works like an array.
Most importantly, if we could get this code working below, we'd know what it takes to make a data type that can hold a dynamic number of values. Only then can we begin to truly appreciate what Array is doing for us.
// make a list
let l = list(1) // (1)
// push an item on the end
l = push(l, 2) // (1 2)
// push another item on the end
l = push(l, 3) // (1 2 3)
// display each item of the list
listeach(l, function (x) {
console.log(x)
})
// should output
// 1
// 2
// 3
runnable demo
All we have to do is make that bit of code (above) work without using any arrays. I'll restrict myself even further and only use functions, if/else, and equality test ===. I see these things in your code, so I'm assuming it's OK for me to use them too.
But am I supposed to believe your teacher would let you write code like this? It works, of course, but I don't think it brings you any closer to your answer
var empty = function () {}
function isEmpty (x) {
return x === empty
}
function pair (x,y) {
return function (p) {
return p(x,y)
}
}
function head (p) {
return p(function (x,y) {
return x
})
}
function tail (p) {
return p(function (x,y) {
return y
})
}
function push (l, x) {
if (isEmpty(l))
return list(x)
else
return pair(head(l), push(tail(l), x))
}
function list (x) {
return pair(x, empty)
}
function listeach (l, f) {
if (isEmpty(l))
return null
else
(f(head(l)), listeach(tail(l), f))
}
// make a list
let l = list(1) // (1)
// push an item on the end
l = push(l, 2) // (1 2)
// push another item on the end
l = push(l, 3) // (1 2 3)
// display each item of the list
listeach(l, function (x) {
console.log(x)
})
closing remarks
It appears as tho you can use an Object in lieu of an Array. The accepted answer (at this time) shows a very narrow understanding of how an object could be used to solve your problem. After this contrived demonstration, are you confident that you are using Objects properly and effectively?
Do you know how to implement an object? Could you fulfill this contract (below)? What I mean by that, is could you write the functions object, set, and get such that the following expressions evaluated to their expected result?
In case it's not obvious, you're not allowed to use Object to make it happen. The whole point of the exercise is to make a new data type that you don't already have access to
m = object() // m
set(m, key, x) // m
get(m, key) // x
set(m, key2, y) // m
get(m, key2) // y
set(m, key3, set(object(), key4, z)) // m
get(get(m, key3), key4) // z
I'll leave this as an exercise for you and I strongly encourage you to do it. I think you will learn a lot in the process and develop a deep understanding and appreciation for what higher-level data types like Array or Object give to you
Since this is a homework I feel like I shouldn't solve it for you, but rather help you in the right direction.
Like Slasher mentioned you can use objects
With JavaScript object one book would look something like
const book = {
title: 'my awesome title',
type: 'novel'
};
book is the object
title is a property with a value 'my awesome title'
type is a property with a value 'novel'
But objects can also have other objects as values. Something like
const BookShelf= {
Book1: {
Title: 'my awesome title',
Type: 'novel'
},
Book2: {
Title: 'my horrible title',
Type: 'sci-fi'
}
};
You can reference the books in the bookshelf in two ways
const book1 = BookShelf.Book1 // Returns the book1 object
const title1 = Book1.Title; // Get the title
const sametitle = BookShelf.Book1.Title // Returns title for book1, same as above.
You can also use brackets:
const book1 = BookShelf['Book1'];
const title1 = BookShelf['Book1']['Title];
You can even make new properties on a object like this:
const Book3 = {
Title: 'running out of ideas'
Type: 'memoir'
};
BookShelf['Book3'] = Book3;
Now the BookShelf has a Book3 property. So your BookShelf object looks like
const BookShelf= {
Book1: {
Title: 'my awesome title',
Type: 'novel'
},
Book2: {
Title: 'my horrible title',
Type: 'sci-fi'
},
Book3 = {
Title: 'running out of ideas'
Type: 'memoir'
};
};
That should get you started :)
JavaScript Objects is a good way to go
1- define a new object:
var myVar = {};
or
var myVar = new Object();
2- usage
// insert a new value, it doesn't matter if the value is a string or int or even another object
// set a new value
myVar.myFirstValue="this is my first value";
// get existing value and do what ever you want with it
var value = myVar.myFirstValue

JavaScript database correlation

I've been trying to 'correlate' between user picked answers and an object property name so that if the two matches then it will display what is inside.
My program is a recipe finder that gives back a recipe that consists of the ingredients the user picked.
my code currently looks like:
//property are the ingredients and the value are the recipes that contain those ingredients. The map is automatically generated
``var map = {
"pork" : [recipe1, recipe2, ...],
"beef" : [],
"chicken" :[],
}
//this gets the user pick from the dom
var cucumber = specificVegetable[7];
var lemon = specificFruits[0];
//Then this code finds the intersection of the recipe(recipes that use more than one ingredients)
function intersect(array1, array2)
{
return array1.filter(function(n) {
return array2.indexOf(n) != -1
});
}
var recipiesWithLemon = map["lemon"]; **// makes the lemon object is map**
var recipiesWithCucumber = map["cucumber"]; **// makes the cucumber object in map**
//Here is where I am stuck
function check(){
var both = intersect(recipiesWithLemon, recipiesWithCucumber);
if ( cucumber.checked && lemon.checked){
for (var stuff in map){
if(stuff="cucumber" && stuff="lemon"){
return both;
}
}
}
}
check();
so basically what I tried to do was I made my intersect and then if user pick is lemon and cucumber then look at the properties in the map object. if the name of the property equals to the exact string then return both. That was the plan but the code does not work and I'm not sure how to fix it.
My plan is to write code for every possible outcome the user may makes so I need to find the correlation between the user pick and the map which stores the recipe. I realize this is not the most effective way but I'm stumped on how to do it another way.
Thanks for the help.
Im using the open source project jinqJs to simplify the process.
I also changed your map to an array of JSON objects. If you must have the map object not as an array, let me know. I will change the sample code.
var map = [
{"pork" : ['recipe1', 'recipe2']},
{"beef" : ['recipe3', 'recipe4']},
{"peach" :['recipe5', 'recipe6']},
{"carrot" :['recipe7', 'recipe8']}
];
var selectedFruit = 'peach';
var selectedVeggie = 'carrot';
var selections = [selectedFruit, selectedVeggie];
var result = jinqJs().from(map).where(function(row){
for(var f in row) {
if (selections.indexOf(f) > -1)
return true;
}
return false;
}).select();
document.body.innerHTML += '<pre>' + JSON.stringify(result, null, 2) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>

Categories

Resources