Compare these simple javascript code related to object - javascript

I have written this code can anyone tell what I have written is correct or not.
var employee = {
name: "John Smith",
job: "Programmer",
age: 31,
printing: function(){
for (just in employee){
alert(this.emloyee(just)"is"this.employee[just])
}
}
}
And tell me that the upper code can work the same.
var employee = {
name: "John Smith",
job: "Programmer",
age: 31,
showAlert: function(){
alert("Name is " + this.name);
alert("Job is " + this.job);
alert("Age is " + this.age);
}
}
employee.showAlert()

It seems you are looking for
var employee = {
name: "John Smith",
job: "Programmer",
age: 31,
showAlert() {
for (const just in this) {
if (typeof this[just] != "function") {
alert(just + " is " + this[just])
}
}
},
};
employee.showAlert()
Notice the const declaration in the loop, the usage of the property name just instead of employee(just), the string concatenation with +, and the use of this instead of employee.
Also the showAlert method itself is just a property that gets enumerated by the for … in loop, so I added a condition to only alert non-function properties.

Related

I've object {name: 'John', 'surname': 'Johnson', 'age': '20'}

Please tell me, I need to write a function that writes the corresponding values
into the variables name, surname and age.
How can this be implemented?
let user = {
name: 'John',
surname: 'Johnson',
age: '20',
};
let{name, surname, age} = user;
document.write(name + ' ' + surname + ' ' + age);
Ummm
function writeUser(user){
document.write(user.name + " " + user.surname + " " +user.age)
}
?
Let's see if this is something in the lines of what you're looking for:
const user = {
name: 'John',
surname: 'Johnson',
age: '20',
};
function updateUser(user) {
user.name = "New name";
user.surname = "New surname";
user.age = "New age";
}
updateUser(user);
const { name, surname, age } = user;
document.write(name + ' ' + surname + ' ' + age);
By adding an other parameter to this function you might make it more useful, like this:
function updateUser(user, overrides) {
Object.assign(user, overrides);
}
updateUser(user, { age: '30', name: 'New name' });
This would change the age and name but leave the surname, but it modifies the input user which isn't really a good pattern, better to return a new object instead:
function updateUser(user, overrides) {
return Object.assign({}, user, overrides); // First assign user to the empty object, then assign the overrides to that new object
}

This in function inside object Javascript

what is the wrong in this code , function fullAdress
i don't know what is the wrong in my code,
help my to fix it
var person = {
firstName: 'Ammar',
lastName: 'Gais',
age:21,
adress:{
street:'king road',
city:'atabra',
state:'River Nile'
fullAdress: function(){
return this.street+" "+this.city+" "+this.state;
}
},
fullName: function() {
return this.firstName+" "+this.lastName;
}
}
You are missing a comma after 'River Nile'. It is always recommended to look at the browser console for such errors. Even the object has properties or methods, everything should be separated by comma:
var person = {
firstName: 'Ammar',
lastName: 'Gais',
age: 21,
adress: {
street: 'king road',
city: 'atabra',
state: 'River Nile',
fullAdress: function() {
return this.street + " " + this.city + " " + this.state;
}
},
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
console.log(person.adress.fullAdress());
console.log(person.fullName());

Accessing Object inside Array

I'm trying to access values inside Firebase array > object.
When I try to access values inside v-for, it works well. But I cannot do this: postDetail.author. It returns undefined. What's the solution?
Since postDetail is an array of object to access properties inside its objects, you need do something like postDetail[Index].prop
var postDetail =[{"author" : "abc", "meta" : "xyz"}];
console.log(postDetail[0].author);
If you want get only author try it:
var postDetails = [{
author: "John",
category: "Tech"
}];
var inner = postDetails.map(function(e) {
return e.autor;
});
console.log(inner);
// Array of object
var persons = [
{
name: "shubham",
age: 22,
comments: ["Good", "Awesome"]
},
{
name: "Ankit",
age: 24,
comments: ["Fine", "Decent"]
},
{
name: "Arvind",
age: 26,
comments: ["Awesome", "Handsome"]
},
{
name: "Ashwani",
age: 28,
comments: ["Very Good", "Lovely"]
}
];
var data = persons.map(person => {
console.log(person.name);
console.log(person.age);
person.comments.map((comment, index) => console.log(index + " " + comment));
});

Ramda JS: How to perform a map where I call R.replace for a given property on each object?

Given the following data:
const my_data = [
{
name: "John",
age: 22
},
{
name: "Johnny",
age: 15
},
{
name: "Dave",
age: 27
}
]
I want to transform the data such that the substring "John" is replaced with "Ben" in each of the name properties so it looks like this:
[
{
name: "Ben",
age: 22
},
{
name: "Benny",
age: 15
},
{
name: "Dave",
age: 27
}
]
I want to do so in the proper functional way (I think is points-free but I am still learning), so I can reuse this in a pipeline, say first reducing by age and then doing the replace, or doing the replace first then doing a sort. How would I do this using the Ramda functions?
var fix_names = ???
var fixed_data = R.map( fix_names, my_data );
R.map(R.over(R.lensProp('name'), R.replace('John', 'Ben')))(my_data)
See R.over and R.lensProp.
There's no reason to prefer point-free functions. Readability is what really matters:
var myData = [ new Person("John", 22)
, new Person("Johnny", 15)
, new Person("Dave", 27)
];
var fixedData = myData.map(fixName);
alert(JSON.stringify(fixedData, null, 4));
function fixName(person) {
return Object.assign(new Person, person, {
name: person.name.replace(/John/g, "Ben")
});
}
function Person(name, age) {
this.name = name;
this.age = age;
}
Point-free functions are useful in very limited cases like eta conversion and function composition. Point-free functions should not be treated as the cornerstone of functional programming.

Clean Method to Normalize Javascript Object Properties

I have an array of javascript objects that represent users, like so:
[
{ userName: "Michael",
city: "Boston"
},
{ userName: "Thomas",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
phone: "444-4444"
}
]
Some of the objects contain some properties but not others. What I need is a clean way to ensure ALL objects get the same properties. If they don't exist, I want them to have an empty string value, like so:
[
{ userName: "Michael",
city: "Boston",
state: "",
phone: ""
},
{ userName: "Thomas",
city: "",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
city: "",
state: "",
phone: "444-4444"
}
]
Update
I should have been a little more specific. I was looking for an option that would handle this situation dynamically, so I don't have to know the properties ahead of time.
For jQuery specific, the $.extend() option is a good one, but will only work if you know ALL the properties ahead of time.
A few have mentioned that this should probably be a server-side task, and while I normally agree with that, there are two reasons I'm not handling this at the server-side:
1) it will be a smaller JSON object if say 900 of 1000 objects only contain 1 of a possible 9 properties.
2) the "empty" properties need to be added to satisfy a JS utility that could be replaced in the future with something that doesn't care if some properties are missing.
Since you are using jQuery you can abuse $.extend
function Person(options){
return $.extend({
userName:"",
city: "",
state:"",
phone: ""
},options);
}
$.map([{}],Person)
update
Heres a way to have dynamic default properties
function mapDefaults(arr){
var defaultProperties = {}
for(var i =0; i < arr.length; i++){
$.each(arr[i],function(key){
defaultProperties[key] = "";
});
}
function Defaulter(obj){
return $.extend({},defaultProperties,obj);
}
return $.map(arr, Defaulter);
}
mapDefaults([{a:"valA"},{b:"valB"}]);
/* produces:
[{a:"valA",b:""},{a:"",b:"valB"}]
*/
Something you might try is creating a coalescing function:
function coalesceValues(val){
switch(val)
case undefined:
case null:
return '';
break;
default:
return val;
break;
}
}
Or if you wanted to forego customization for simplicity:
function coalesceValues(val){
return val || '';
}
And then apply it when assigning variables:
var city = coalesceValues(obj.city);
This way you don't need to do any crazy breakdown to array and loop or anything, you can apply it to whatever you want, and you can also customize the values you want to coalesce.
Just offering an alternative idea.
The way that is easiest to understand is probably to make a function that accepts an object and uses if statements as existence checks, assigning a default value if it doesn't find it.
function normalize(object) {
if(typeof object.userName === 'undefined') {
object.userName = 'Default Value';
}
if(typeof object.city === 'undefined') {
object.city = 'Default Value';
}
if(typeof object.state === 'undefined') {
object.state = 'Default Value';
}
if(typeof object.phone === 'undefined') {
object.phone = 'Default Value';
}
return object;
}
var userArray = [{},{},{}].map(normalize);
We can also go the constructor route and provide default values on object creation.
function User (data) {
this.userName = data.userName || 'Default Value';
this.city = data.city || 'Default Value';
this.state = data.state || 'Default Value';
this.phone = data.phone || 'Default Value';
return this;
}
var userArray = [{},{},{}].map(function(o){
return new User(o);
});
Of course this depends on one specific type of data and won't extend to other properties and isn't very DRY, but as I said, this is probably the easiest to understand from a beginner's standpoint.
var list = [
{ userName: "Michael",
city: "Boston"
},
{ userName: "Thomas",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
phone: "444-4444"
}
];
for(var i = 0; i < list.length; i++){
if(list[i].state === undefined)
list[i].state = "";
if(list[i].phone === undefined)
list[i].phone = "";
};
console.log(list);
http://jsfiddle.net/g5XPk/1/
This should probably be a server-side task, but..
If you know all the possible properties ahead of time, you could do this:
http://jsfiddle.net/BMau9/
var properties = ['userName', 'city', 'state', 'phone'];
var data = [{
userName: "Michael",
city: "Boston"
}, {
userName: "Thomas",
state: "California",
phone: "555-5555"
}, {
userName: "Kathrine",
phone: "444-4444"
}];
for (var i in data) {
for (var j in properties) {
data[i][properties[j]] = data[i][properties[j]] || '';
}
}
Fiddle
This function stores unique object keys in an array and so you can run your array of objects through it and then use one of the other supplied answers to add the keys to the objects if they do not exist:
function uniqueKeys(){
var keys=[];
function getUniqueKeys(){
return keys
}
function addObject(obj){
for (var k in obj){
keys = _.union(keys,[k]);
}
}
return {
addObj: addObject,
getKeys: getUniqueKeys
}
}
Usage:
var objArr = [{ userName: "Michael", city: "Boston" },
{ userName: "Thomas", state: "California", phone: "555-5555"},
{ userName: "Kathrine",phone: "444-4444" }];
var uniq = new uniqueKeys();
_.each(objArr, function(v){
uniq.addObj(v)
});
var keys = uniq.getKeys();
alert(keys);
vanilla js
let A = [
{
userName: "Michael",
city: "Boston",
},
{
userName: "Thomas",
state: "California",
phone: "555-5555",
},
{
userName: "Kathrine",
phone: "444-4444",
},
];
// set-difference
const diff = (a,b) => new Set([...a].filter((x) => !b.has(x)));
// all keys
const K = new Set(arr.map(o => Object.keys(o)).flat());
// add missing keys and default vals
A.forEach((e,i) => diff(K, new Set(Object.keys(e))).forEach(k => A[i][k] = ""));

Categories

Resources