i try to access this function in my Object with the console.log but i don't really understand why i can't access it!
I'm beginning Javascript but i'm really stuck with accessing functions in Object.
Thanks for the help
const hotel = {
name: "Grand Hotel",
location: "Stockholm",
pricePerNight: 2200,
roomBooked: 23,
totalRoom: 223,
roomAvailable: function(){
return this.totalRoom - this.roomBooked;
}
};
hotel.roomAvailable();
console.log(hotel.roomAvailable);
You're just missing the parentheses in the log function:
hotel.roomAvailable()
You are already invoking the function which will return the value. Just log the return value instead.
In your code you are just logging the definition of the function but not really invoking it.
const hotel = {
name: "Grand Hotel",
location: "Stockholm",
pricePerNight: 2200,
roomBooked: 23,
totalRoom: 223,
roomAvailable: function() {
return this.totalRoom - this.roomBooked;
}
};
var isRoomAvailable = hotel.roomAvailable();
console.log(isRoomAvailable);
Is this what you want?
const hotel = {
name: "Grand Hotel",
location: "Stockholm",
pricePerNight: 2200,
roomBooked: 23,
totalRoom: 223,
roomAvailable: function(){
return this.totalRoom - this.roomBooked;
}
};
console.log(hotel.roomAvailable());
Related
Trouble:
[
{
"project_id": 1,
"project_name": "CDP",
"role": "PL"
},
{
"project_id": 2,
"project_name": "Admincer",
"role": "PM"
},
I want to add the "project_id" property from the above three properties to another array using some method.
My idea is: 1. First of all, if I could copy the "project_id" property of this array to the second Nested JSON array, it would be fine.
What I looked up:
const obj = {
"project_id": 1,
"project_name": "CDP",
"role": "PL"
};;
const objCopy = {
"start_time": "09:00:00",
"end_time": "18:00:00",
"rest_time": "01:00:00",
"worked_time": "08:00:00",
"is_wfh": true,
"id": 1, 1,
"work_day_id": 45,
"time_cards": [
{
... obj
}
]
};;
console.log (objCopy);
I found that I could copy it this way.
I tried the above code in Chrome Console.
The array was copied, but the entire object was copied. I just want to copy the properties of project_id.
I want to create a new property called "prj_name" in this array and display only that property in Vuetify.
async fetchWorkerTimeCard() {
try {
this.worker_data = []
await this.$axios.$get('/worker_time_card', {
params: {
work_date: this.calendarVal
}
}).then(data => {
this.worker_data = data
})
var projects = await this.fetch_worker_projects()
console.log(projects)
} catch (error) {
console.log(error)
this.worker_data = []
}
},
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.5/vue.js"></script>
<v-card>
<v-data-table v-if="worker_data.time_cards" :headers="headers2" :items="worker_data.time_cards"></v-data-table>
</v-card>
You can simply change your object data like any other object in JS.
const obj = {
"project_id": 1,
"project_name": "CDP",
"role": "PL"
};
const objCopy = {
"start_time": "09:00:00",
"end_time": "18:00:00",
"rest_time": "01:00:00",
"worked_time": "08:00:00",
"is_wfh": true,
"id": 1,
"work_day_id": 45
}
console.log({...obj, ...objCopy})
This will create 1 object that merged.
Or if you just want to project_id value then just change it like:
objCopy.project_id = obj.project_id
If I'm understanding your first question correctly, you might be interested in the map function, which allows you to create a new array from an existing array. So, for example, if the first snippet you posted is an array of objects we call projects, you could use:
var projectIds = projects.map(p => p.project_id), where projectIds would now be an array of just project ids.
It seems like you might be asking more than this though, so I second Bravo's request for more clarification/reorganization in your question.
I'm not pretty sure if you want either of the following results:
{
"start_time": "09:00:00",
"end_time": "18:00:00",
"rest_time": "01:00:00",
"worked_time": "08:00:00",
"is_wfh": true,
"id": [
1,
1
],
"work_day_id": 45,
"time_cards": [
{
"project_id": 1
},
{
"project_id": 2
}
]
}
or this
{
"start_time": "09:00:00",
"end_time": "18:00:00",
"rest_time": "01:00:00",
"worked_time": "08:00:00",
"is_wfh": true,
"id": [
1,
1
],
"work_day_id": 45,
"time_cards": [
"project_id": [1, 2]
}
In case you need the first scenario, the following code may help you:
// This function return an array with: [{project_id: Number}]
function onlyIds(obj) {
const ids = [];
// Iterate the obj Array
obj.forEach(element => {
// Push a new JSON: "{project_id: 1}" or whatever
ids.push({ project_id: element.project_id });
});
// return an array that only contains the project_id
return ids;
}
const obj = [
{
project_id: 1,
project_name: 'CDP',
role: 'PL',
},
{
project_id: 2,
project_name: 'Admincer',
role: 'PM',
},
];
const objCopy = {
start_time: '09:00:00',
end_time: '18:00:00',
rest_time: '01:00:00',
worked_time: '08:00:00',
is_wfh: true,
id: [1, 1],
work_day_id: 45,
time_cards: onlyIds(obj),
};
console.log(onlyIds(obj));
console.log(objCopy);
I'm pretty sure there should be any more elegant/optimal way (as using any kind of higher-order function I may be missing right now) but as far as I understood, this should do the job.
This question already has answers here:
Return object with highest value
(4 answers)
Closed 3 years ago.
I need to find the max value (b) of the array then take that value convert it then put everything into another function and display it like so: "Lake Baikal:1640.43 meters."
function lakeDepth() {
let lakeData = {
"Caspian Sea": 560,
"Tarn Hows": 53,
"Crater Lake": 324,
"Lake Tanganyika": 803,
"Lake Vostok": 546,
"Lake Baikal": 897,
};
result = Object
.keys(lakeData)
.sort(function(a, b) {
return lakeData[b] - lakeData[a];
})
.map(Number);
console.log(result);
}
lakeDepth();
function fathomsToMeter() {
let deepestInMeter = result * 1.8288;
return deepestInMeter;
}
function displayData() {
console.log(result + deepestInMeter + "meter");
}
how do i get just the "b" part of the array do the calculation in the function and put it together at the end? thanks in advance for any help.
Your code gives an array of lake names sorted by depth, so all that was needed was to select the first from that array using [0], then select the actual depth using lakeData[nameOfLake] which looks into the lakeData object and returns the value of the key nameOfLake.
Let me know if you have any questions.
const lakeData = {
"Caspian Sea": 560,
"Tarn Hows": 53,
"Crater Lake": 324,
"Lake Tanganyika": 803,
"Lake Vostok": 546,
"Lake Baikal": 897
};
const lake = Object.keys(lakeData).sort((a, b) => lakeData[b] - lakeData[a])[0];
console.log(`${lake}: ${lakeData[lake] * 1.8288} metres`);
Following your comment of 11/11:
An example of a template literal with a new line:
console.log(`The Deepest lake is: ${lake}
This lake is ${lakeData[lake] * 1.8288}m deep.`)
You can easily find deepest lake as below, regarding to your code;
let lakeData = {
"Caspian Sea": 560,
"Tarn Hows": 53,
"Crater Lake": 324,
"Lake Tanganyika": 803,
"Lake Vostok": 546,
"Lake Baikal": 897,
};
let _deepest = 0
let _key = ""
Object.keys(lakeData).forEach(function(key) {
if (lakeData[key] > _deepest)
{
_deepest = lakeData[key]
_key = key
}
});
console.log(lakeData[_key], _key)
Loop through all keys in object, follow their values and compare in every iteration, and find the biggest one.
I've been reading through an article titled Don’t Be Scared Of Functional Programming and there is a piece of code I'm having trouble understanding (pasted below). The code's purpose is to get an item from an array of objects called data. What I don't understand is how the function within the function works. Where is the item argument coming from when you invoke getItem()?
var data = [
{
name: "Jamestown",
population: 2047,
temperatures: [-34, 67, 101, 87]
},
{
name: "Awesome Town",
population: 3568,
temperatures: [-3, 4, 9, 12]
}
{
name: "Funky Town",
population: 1000000,
temperatures: [75, 75, 75, 75, 75]
}
];
function getItem(propertyName) {
// Return a function that retrieves that item, but don't execute the function.
// We'll leave that up to the method that is taking action on items in our
// array.
return function(item) {
return item[propertyName];
}
}
I Understand that JS allows functions to be passed as arguments because they are treated as “first-class objects" in JS, but I don't understand where that item argument would be coming from.
This is defining a function that will accept a parameter called item which can be used to return the propertyName element from the given item. It is the function that is then passed back to the caller of getItem. It would be used as follows:
var getName = getItem('name');
var result = getName(x);
Where x is a variable containing a property called 'name'
Maybe this helps a bit.
It utilized a partial application of the first parameter propertyName with Function.prototype.bind():
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Small example with your data and function:
function getItem(propertyName, item) {
return item[propertyName];
}
var data = [{ name: "Jamestown", population: 2047, temperatures: [-34, 67, 101, 87] }, { name: "Awesome Town", population: 3568, temperatures: [-3, 4, 9, 12] }, { name: "Funky Town", population: 1000000, temperatures: [75, 75, 75, 75, 75] }],
// this returns a function with only item as parameter
getName = getItem.bind(null, 'name');
document.write('<pre>' + JSON.stringify(data.map(getName), 0, 4) + '</pre>');
Is there a way to initialize a javascript object with an array of child objects in one line? How can I do the following in just on initialization line.
var obj = {doc: 100,
defaultrateid: 32,
rates: [],
};
obj.rates[31] = {rate: 101.00, name: "Rate 1"};
obj.rates[32] = {rate: 121.00, name: "Rate 2"};
Basically what I want is a single javascript object that has my user parameters. This object will be reused on multiple web forms. In the case of 'rates', the forms will have a dropdown to select a rate. The web forms have client side calculations that require the matching rate object based on the rate's unique id (e.g. 32).
I'm trying to use a associative array instead of having to do looping for finding a match based on unique value.
Seems a bit hacky:
obj = {
doc: 100,
defaultrateid: 32,
rates: (new Array(30)).concat([{
rate: 101.00,
name: "Rate 1"
}, {
rate: 121.00,
name: "Rate 2"
}])
};
EDIT:
Maybe you don't really need an array, you can use an object like this:
obj = {
doc: 100,
defaultrateid: 32,
rates: {
"31": {
rate: 101.00,
name: "Rate 1"
},
"32": {
rate: 121.00,
name: "Rate 2"
}
}
};
And you can still get the rates like obj.rates[31].
Do you mean like this?
var obj = {
doc: 100,
defaultrateid: 32,
rates: [{
rate: 101.00
}, {
rate: 121.00
}],
};
alert(obj.rates[1].rate);
Say I want the object to be something like this:
var Book = {
title: "the catcher in the rye",
price: "80.98",
characters: [{name: "holden caulfield", age: 16, height:"6.2"},
{name: "phoebe caulfield",age:13, height: "5"}]
};
EDITED
question:
characters array is built by adding a character one by one. How can do this while making sure that name, age and height properties are defined as above.
Something to the effect of?
Book.characters.add({name: "phoebe caulfield",age:13, height: "5"});
I would like to be able to define this programmatically, ie add properties to the object rather than define it like this.
Is this possible?
You can do it in dynamic code (rather than a static declaration) like this:
var Book = {};
Book.title = "the catcher in the rye";
Book.price = "80.98";
Book.characters = [];
Book.characters.push({name: "holden caulfield", age: 16, height: "6.2"});
Book.characters.push({name: "phoebe caulfield", age: 13, height: "5"});
Do you mean like this?
var Book = {}; // empty object
Book.title = "the catcher in the rye";
Book.price = 80.98;
Book.characters = [];
var character = {
"name": "holden caulfield",
"age": 16,
"height": 6.2
};
Book.characters.push(character);
var Book={};
Book.title="the catcher in the rye";
Book.price="80.98";
var characters=[];
characters.push({name: "holden caulfield", age: 16, height:"6.2"});
characters.push({name: "phoebe caulfield",age:13, height: "5"});
Book.characters=characters;
...etc.
It certainly is! Javascript is a completely dynamic language - if you want a new property on an object, just set it!
e.g.
var myObject = {}; // empty object
myObject.myProperty = 5; // creates the new property and sets it to 5.
myObject.nestedObject = { prop1: 6, 'long-property-name': 'lolcats' };
I think you're looking for a JSON stringifier:
http://www.json.org/js.html
This will allow you to create your object:
var myobj = { };
myobj.myprop = "value";
alert(JSON.stringify(myobj));
using the map function is the easiest way I've found to build an array of objects. The snippet below, constructs the objet you want in just 2 statements:
var Book = {
title: "the catcher in the rye",
price: 80.98
};
Book.characters = [6.2, 5].map(el => {
return {
name: 'caulfield', age: 14, height: el
};
});
// Output
JSON.stringify(Book);
{
"title": "the catcher in the rye",
"price": 80.98,
"characters": [
{ "name":"caulfield", "age":14, "height":6.2 },
{ "name":"caulfield", "age":14, "height":5 }
]
}