1677207857
In questo tutorial, impareremo l'oggetto JavaScript, come creare un oggetto e come modificare/eliminare le proprietà in un oggetto.
Spiegazione dell'oggetto JavaScript
Gli oggetti sono strutture dati importanti in JavaScript. Ciò è in parte dovuto al fatto che gli array sono oggetti in JavaScript e li utilizzerai sempre.
Gli oggetti sono estremamente importanti per raggruppare dati e funzionalità, quindi puoi fare molto con un oggetto in JavaScript. Il nodo DOM e qualsiasi nodo DOM creato con createElementsono esempi di un oggetto in JavaScript.
In questo articolo, tratteremo tutto quanto segue sugli oggetti:
Gli oggetti nella vita di tutti i giorni hanno proprietà e azioni di "metodo". Prendi, ad esempio, un fan. È un oggetto con proprietà come marca, colore o modello e azioni che può eseguire come raffreddare le stanze e controllare l'umidità.
Come spiegato sopra, gli oggetti in JavaScript sono strutture di dati fondamentali che comprendono proprietà e metodi. Mentre i metodi sono funzioni/azioni che un oggetto può eseguire (come guidare e raffreddare stanze con oggetti della vita reale come automobili e ventilatori), le proprietà sono caratteristiche di un oggetto come il suo nome e il suo valore.
Gli oggetti ti consentono di raggruppare i dati correlati e suddividere il codice in parti logiche. In JavaScript, abbiamo valori primitivi e valori di riferimento. Number, Boolean, Null, Undefined, String e Symbol sono valori primitivi, mentre oggetti come nodi DOM, array e così via sono valori di riferimento.
Sia nella vita reale che in JavaScript, puoi utilizzare gli oggetti in modi diversi a seconda delle loro proprietà e metodi. Impareremo di più sugli oggetti JavaScript ora.
Useremo il codice seguente come esempio:
const person = {
name:'kamal',
age:30,
friends:[
'Shola','Ade','Ibraheem'
],
greet:function(){
alert('Hello World')
}
}
Creazione di oggetti
In the above code, we have a person object that we created with curly braces. The object has key-value pairs. You can store key-value pairs in a JavaScript object, associating each key with a unique value.
These key-value pairs allow you to retrieve values using the associated keys. For instance, the above object represents a person with properties like "name", "age"," friends", and a function "greet". Each property becomes a key-value pair with the property name as the key and the property value as the value. Both properties and methods are created inside the object.
To create a key in an object, you don't need a let or const keyword. Because objects are dynamic, you can add or change properties without declaring a variable. Rather, you start with your preferred name, a colon, and then your value.
We created an array of friends inside the object to show we can have an object inside of an object. We created a method (which is a function) inside of an object with greet as the key.
There are two major approaches to adding properties to an object in JavaScript. The first is to create a brand-new object.
let person = {
name:'kamal',
age:30,
friends:[
'Shola','Ade','Ibraheem'
],
greet:function(){
alert('Hello World')
}
}
person = {
name:'kamal',
age:30,
friends:[
'Shola','Ade','Ibraheem'
],
greet:function(){
alert('Hello World')
},
isAdmin:true
}
With the above code, we created the first person object using the let keyword, allowing us to reassign it to a new value. We then added the "isAdmin" property to the person object. If you run console.log(person), you will see that "isAdmin" is now part of the object's properties.
The second approach is to add properties using dot notation.
const person = {
name:'kamal',
age:30,
friends:[
'Shola','Ade','Ibraheem'
],
greet:function(){
alert('Hello World')
}
}
person.isAdmin = true;
With dot notation, you can access properties that an object has not added before. For example, if the person object doesn't have an "isAdmin" property, accessing it will return "undefined".
You can add the "isAdmin" property to the person object using dot notation, and you can also overwrite any property by assigning a new value to it. This approach is shorter and simpler compared to other methods.
The choice between using the let keyword and dot notation depends on whether you need to create a new object reference or modify an existing one.
You would use the let keyword to create a new object when you need to create a new reference to an object, separate from any existing references to similar objects.
On the other hand, you would use dot notation to add or modify properties on an existing object reference. This is useful when you want to make changes to an object without creating a new reference.
You can also use dot notation to modify properties in an object. The below code shows that the property name with the pair value kamal will be changed to lawal when modified using dot notation.
const person = {
name:'kamal',
age:30,
friends:[
'Shola','Ade','Ibraheem'
],
greet:function(){
alert('Hello World')
}
}
person.isAdmin = true;
person.name = 'lawal';
console.log(person);
It is very simple to delete a property in an object. JavaScript has a special keyword called "delete" that allows you to discard any properties you wish.
const person = {
name:'kamal',
age:30,
friends:[
'Shola','Ade','Ibraheem'
],
greet:function(){
alert('Hello World')
}
}
person.isAdmin = true;
delete person.friends;
console.log(person);
The property friends will be deleted from the object with the above code.
You can use anything as a key name that you can use as a variable name. But not every key name can serve as a variable name because keys are more flexible than variables.
let person = {
name:'kamal',
age:37,
}
Suppose you want to use "last name" as a key instead of "name". JavaScript syntax does not allow two separate words in this naming convention.
Ma puoi superare questo problema usando una chiave speciale in un oggetto. JavaScript converte automaticamente qualsiasi chiave inserita in una stringa, anche la chiave "età". Di conseguenza, gli oggetti in JavaScript sono un dizionario di chiavi stringa e valori di qualsiasi tipo.
let person = {
last name:'kamal',
age:30,
friends:[
'Shola','Ade','Ibraheem'
],
greet:function(){
alert('Hello World')
}
}
Per utilizzare "cognome" come chiave nel codice precedente, è necessario informare JavaScript che si tratta di una chiave racchiudendola tra virgolette, le virgolette singole o doppie funzioneranno. Si consiglia di utilizzare un nome che può essere utilizzato anche come variabile anziché questo metodo di eccezione per l'impostazione di una chiave.
let person = {
'last name':'kamal',
age:30,
friends:[
'Shola','Ade','Ibraheem'
],
greet:function(){
alert('Hello World')
}
}
L'utilizzo di virgolette singole per racchiudere "cognome" e l'utilizzo come nome chiave è un codice JavaScript valido e funzionerà correttamente.
Per aggiungere e modificare le proprietà in un oggetto, è possibile utilizzare il metodo di notazione dell'oggetto. Tuttavia, esiste un altro metodo in JavaScript per accedere alle proprietà degli oggetti, noto come notazione tra parentesi quadre, che consente di accedere a una proprietà creata da una chiave speciale in JavaScript.
let person = {
'last name':'kamal',
age:30,
friends:[
'Shola','Ade','Ibraheem'
],
}
// console.log(person.last name); is not valid in JavaScript
Non è possibile accedere al nome della chiave 'cognome' utilizzando il metodo della notazione con punto, ma è possibile utilizzare la notazione tra parentesi quadre, disponibile per qualsiasi oggetto.
console.log(person['last name']);
Il codice sopra mostrerà il valore della chiave del cognome che è kamal. Tuttavia, è fondamentale racchiudere la chiave tra virgolette singole o doppie.
Puoi abilitare un'altra funzione dinamica con parentesi quadre e oggetti in JavaScript. Funziona quando è necessario definire una nuova proprietà, soprattutto quando non si conosce il nome della proprietà.
Ad esempio, non conoscerai in anticipo l'input specifico dell'utente. Ma dovrai aggiungere la proprietà con quel nome all'oggetto.
const userName ='level';
let person = {
'first name':'kamal',
age:30,
[userName]: 'see',
}
console.log(person);
Non racchiudendo userName in una parentesi quadra, verrà aggiunta la proprietà con il nome userName invece del valore memorizzato al suo interno. L'aggiunta di una parentesi quadra a userName cercherà e prenderà il valore memorizzato nella variabile come nome chiave e lo aggiungerà a un oggetto persona.
Esiste una sintassi alternativa che puoi utilizzare per definire un metodo in modo più efficiente. Tradizionalmente, per creare un metodo in un oggetto, hai bisogno di una chiave e di un valore, dove crei il valore come metodo usando la parola chiave function.
let person = {
name:'jamaldeen',
age:30,
hobbies:[
'reading','playing','sleeping'
],
speek:function(){
return this.hobbies
}
}
console.log(person.speak());
Nel codice precedente, il metodo viene creato con una parola chiave di funzione dopo i due punti. In alternativa, potresti fare così:
let person = {
name:'jamaldeen',
age:30,
hobbies:[
'reading','playing','sleeping'
],
speek(){
return this.hobbies
}
}
console.log(person.speak());
In JavaScript, creating a method with object short methods is a shorthand notation. Omitting the "function" keyword and the colon(:) before the function body is allowed using the short methods.
This is because with the short method syntax, the property is automatically defined as method, which renders the "function" keyword useless.
The code remains functional because the JavaScript engine recognizes the shorthand syntax and interprets it as a regular function definition.
Some of the advantages of using object short methods over regular methods are as follows
While using object short methods is good, using regular methods may still be more appropriate. It's important to choose the right approach based on your particular requirements.
The object spread operator is a popular and powerful syntax in JavaScript. The spread operator takes all the key-value pairs of an object and copies the key name and value into a new object.
Un oggetto è un valore di riferimento e se si desidera una copia dell'oggetto senza puntare alla stessa proprietà in memoria, l'operatore spread è la risposta.
let person = {
name:'kamal',
age:30,
hobbies:[
'reading','playing','sleeping'
]
}
console.log(person);
const person2 ={...person};
console.log(person2.age);
La sintassi per l'operatore object spread va tra le parentesi di apertura e di chiusura. Quindi dovrebbero esserci tre punti e l'oggetto che vuoi diffondere in questo oggetto.
La destrutturazione degli oggetti è una funzionalità importante in JavaScript che consente di estrarre valori da un oggetto e assegnarli a singole variabili.
Per eseguire la destrutturazione dell'oggetto, si utilizza un modello di destrutturazione sul lato sinistro di un'istruzione di assegnazione e l'oggetto da cui si desidera estrarre i valori sul lato destro. Per esempio:
const person = { name: 'lawal', age: 39 };
const { person, age } = person;
console.log(name); // 'lawal'
console.log(age); // 39
L' constistruzione utilizza la destrutturazione dell'oggetto per estrarre le proprietà namee agedall'oggetto persone assegnarle a due variabili separate. Questo è un modo conciso ed efficiente per estrarre valori da un oggetto, specialmente quando si ha a che fare con oggetti complessi.
La destrutturazione dell'oggetto consente inoltre di fornire valori predefiniti, nel caso in cui la proprietà che si desidera estrarre non esista nell'oggetto. È inoltre possibile rinominare le variabili estratte utilizzando un alias, offrendo un maggiore controllo sulla struttura e sulla denominazione dei valori estratti.
Qual è la thisparola chiave? thisè una parola chiave specifica in JavaScript che è molto importante se utilizzata all'interno di una funzione in un oggetto. Ma puoi usarlo ovunque nel tuo codice a parte il corpo della funzione di un oggetto.
thisè una potente parola chiave utilizzata per fare riferimento all'oggetto corrente in cui viene utilizzata.
let person = {
name:'kamal',
age:30,
greet:function(){
return `My name is ${this.name}, and my age is ${this.age} years old`;
},
}
console.log(person.greet());
// My name is kamal, and my age is 30 years old.
Il codice precedente dimostra che la parola chiave "this" si riferisce all'oggetto contenente la funzione, in questo caso l'oggetto "person", e il risultato mostra l'output della funzione "greet".
Indipendentemente dalla sua posizione all'interno di un oggetto, la thisparola chiave si riferisce sempre all'entità che ha eseguito la funzione nel codice. L'utilizzo thisin contesti diversi all'interno del codice può produrre risultati distinti. Ad esempio:
let person = {
name:'kamal',
age:30,
greet:function(){
return `My name is ${this.name}, and my age is ${this.age} years old`;
},
}
console.log(this);
L'output del codice mostra che la thisparola chiave quando console.logged stamperà un oggetto finestra.
In questo tutorial, abbiamo appreso l'oggetto JavaScript, come creare un oggetto e come modificare/eliminare le proprietà in un oggetto.
Abbiamo parlato brevemente dell'importanza dell'operatore spread e della destrutturazione dell'oggetto nell'oggetto JavaScript, nonché della popolare thisparola chiave e di come usarla negli oggetti JavaScript.
Fonte: https://www.freecodecamp.org
#javascript
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1616670795
It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.
Does your business need an interactive website or app?
Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.
The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.
Get your business app with JavaScript
For more inquiry click here https://bit.ly/31eZyDZ
Book Free Interview: https://bit.ly/3dDShFg
#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers
1589255577
As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.
#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips
1626321063
PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.
With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.
Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.
Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.
#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company
1670062320
I’m a huge fan of automation when the scenario allows for it. Maybe you need to keep track of guest information when they RSVP to your event, or maybe you need to monitor and react to feeds of data. These are two of many possible scenarios where you probably wouldn’t want to do things manually.
There are quite a few tools that are designed to automate your life. Some of the popular tools include IFTTT, Zapier, and Automate. The idea behind these services is that given a trigger, you can do a series of events.
In this tutorial, we’re going to see how to collect Twitter data with Zapier, store it in MongoDB using a Realm webhook function, and then run aggregations on it using the MongoDB query language (MQL).
There are a few requirements that must be met prior to starting this tutorial:
There is a Zapier free tier, but because we plan to use webhooks, which are premium in Zapier, a paid account is necessary. To consume data from Twitter in Zapier, a Twitter account is necessary, even if we plan to consume data that isn’t related to our account. This data will be stored in MongoDB, so a cluster with properly configured IP access and user permissions is required.
You can get started with MongoDB Atlas by launching a free M0 cluster, no credit card required.
While not necessary to create a database and collection prior to use, we’ll be using a zapier database and a tweets collection throughout the scope of this tutorial.
Since the plan is to store tweets from Twitter within MongoDB and then create queries to make sense of it, we should probably get an understanding of the data prior to trying to work with it.
We’ll be using the “Search Mention” functionality within Zapier for Twitter. Essentially, it allows us to provide a Twitter query and trigger an automation when the data is found. More on that soon.
As a result, we’ll end up with the following raw data:
{
"created_at": "Tue Feb 02 20:31:58 +0000 2021",
"id": "1356701917603238000",
"id_str": "1356701917603237888",
"full_text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript",
"truncated": false,
"display_text_range": [0, 188],
"metadata": {
"iso_language_code": "en",
"result_type": "recent"
},
"source": "<a href='https://about.twitter.com/products/tweetdeck' rel='nofollow'>TweetDeck</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": "227546834",
"id_str": "227546834",
"name": "Nic Raboy",
"screen_name": "nraboy",
"location": "Tracy, CA",
"description": "Advocate of modern web and mobile development technologies. I write tutorials and speak at events to make app development easier to understand. I work @MongoDB.",
"url": "https://t.co/mRqzaKrmvm",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/mRqzaKrmvm",
"expanded_url": "https://www.thepolyglotdeveloper.com",
"display_url": "thepolyglotdeveloper.com",
"indices": [0, 23]
}
]
},
"description": {
"urls": ""
}
},
"protected": false,
"followers_count": 4599,
"friends_count": 551,
"listed_count": 265,
"created_at": "Fri Dec 17 03:33:03 +0000 2010",
"favourites_count": 4550,
"verified": false
},
"lang": "en",
"url": "https://twitter.com/227546834/status/1356701917603237888",
"text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}
The data we have access to is probably more than we need. However, it really depends on what you’re interested in. For this example, we’ll be storing the following within MongoDB:
{
"created_at": "Tue Feb 02 20:31:58 +0000 2021",
"user": {
"screen_name": "nraboy",
"location": "Tracy, CA",
"followers_count": 4599,
"friends_count": 551
},
"text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}
Without getting too far ahead of ourselves, our analysis will be based off the followers_count
and the location
of the user. We want to be able to make sense of where our users are and give priority to users that meet a certain followers threshold.
Before we start connecting Zapier and MongoDB, we need to develop the middleware that will be responsible for receiving tweet data from Zapier.
Remember, you’ll need to have a properly configured MongoDB Atlas cluster.
We need to create a Realm application. Within the MongoDB Atlas dashboard, click the Realm tab.
For simplicity, we’re going to want to create a new application. Click the Create a New App button and proceed to fill in the information about your application.
From the Realm Dashboard, click the 3rd Party Services tab.
We’re going to want to create an HTTP service. The name doesn’t matter, but it might make sense to name it Twitter based on what we’re planning to do.
Because we plan to work with tweet data, it makes sense to call our webhook function tweet, but the name doesn’t truly matter.
With the exception of the HTTP Method, the defaults are fine for this webhook. We want the method to be POST because we plan to create data with this particular webhook function. Make note of the Webhook URL because it will be used when we connect Zapier.
The next step is to open the Function Editor so we can add some logic behind this function. Add the following JavaScript code:
exports = function (payload, response) {
const tweet = EJSON.parse(payload.body.text());
const collection = context.services.get("mongodb-atlas").db("zapier").collection("tweets");
return collection.insertOne(tweet);
};
In the above code, we are taking the request payload, getting a handle to the tweets collection within the zapier database, and then doing an insert operation to store the data in the payload.
There are a few things to note in the above code:
When we call our function, a new document should be created within MongoDB.
By default, the function will not deploy when saving. After saving, make sure to review and deploy the changes through the notification at the top of the browser window.
So, we know the data we’ll be working with and we have a MongoDB Realm webhook function that is ready for receiving data. Now, we need to bring everything together with Zapier.
For clarity, new Twitter matches will be our trigger in Zapier, and the webhook function will be our event.
Within Zapier, choose to create a new “Zap,” which is an automation. The trigger needs to be a Search Mention in Twitter, which means that when a new Tweet is detected using a search query, our events happen.
For this example, we’re going to use the following Twitter search query:
url:developer.mongodb.com -filter:retweets filter:safe lang:en -from:mongodb -from:realm
The above query says that we are looking for tweets that include a URL to developer.mongodb.com. The URL doesn’t need to match exactly as long as the domain matches. The query also says that we aren’t interested in retweets. We only want original tweets, they have to be in English, and they have to be detected as safe for work.
In addition to the mentioned search criteria, we are also excluding tweets that originate from one of the MongoDB accounts.
In theory, the above search query could be used to see what people are saying about the MongoDB Developer Hub.
With the trigger in place, we need to identify the next stage of the automation pipeline. The next stage is taking the data from the trigger and sending it to our Realm webhook function.
As the event, make sure to choose Webhooks by Zapier and specify a POST request. From here, you’ll be prompted to enter your Realm webhook URL and the method, which should be POST. Realm is expecting the payload to be JSON, so it is important to select JSON within Zapier.
We have the option to choose which data from the previous automation stage to pass to our webhook. Select the fields you’re interested in and save your automation.
The data I chose to send looks like this:
{
"created_at": "Tue Feb 02 20:31:58 +0000 2021",
"username": "nraboy",
"location": "Tracy, CA",
"follower_count": "4599",
"following_count": "551",
"message": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}
The fields do not match the original fields brought in by Twitter. It is because I chose to map them to what made sense for me.
When deploying the Zap, anytime a tweet is found that matches our query, it will be saved into our MongoDB cluster.
With tweet data populating in MongoDB, it’s time to start querying it to make sense of it. In this fictional example, we want to know what people are saying about our Developer Hub and how popular these individuals are.
To do this, we’re going to want to make use of an aggregation pipeline within MongoDB.
Take the following, for example:
[
{
"$addFields": {
"follower_count": {
"$toInt": "$follower_count"
},
"following_count": {
"$toInt": "$following_count"
}
}
}, {
"$match": {
"follower_count": {
"$gt": 1000
}
}
}, {
"$group": {
"_id": {
"location": "$location"
},
"location": {
"$sum": 1
}
}
}
]
There are three stages in the above aggregation pipeline.
We want to understand the follower data for the individual who made the tweet, but that data comes into MongoDB as a string rather than an integer. The first stage of the pipeline takes the follower_count
and following_count
fields and converts them from string to integer. In reality, we are using $addFields
to create new fields, but because they have the same name as existing fields, the existing fields are replaced.
The next stage is where we want to identify people with more than 1,000 followers as a person of interest. While people with fewer followers might be saying great things, in this example, we don’t care.
After we’ve filtered out people by their follower count, we do a group based on their location. It might be valuable for us to know where in the world people are talking about MongoDB. We might want to know where our target audience exists.
The aggregation pipeline we chose to use can be executed with any of the MongoDB drivers, through the MongoDB Atlas dashboard, or through the CLI.
You just saw how to use Zapier with MongoDB to automate certain tasks and store the results as documents within the NoSQL database. In this example, we chose to store Twitter data that matched certain criteria, later to be analyzed with an aggregation pipeline. The automations and analysis options that you can do are quite limitless.
If you enjoyed this tutorial and want to get engaged with more content and like-minded developers, check out the MongoDB Community.
This content first appeared on MongoDB.
Original article source at: https://www.thepolyglotdeveloper.com/