Snippets Collections
import { useState } from "react";
import ReactDOM from "react-dom/client";

function Car() {
  const [car, setCar] = useState({
    brand: "Ford",
    model: "Mustang",
    year: "1964",
    color: "red"
  });

  const updateColor = () => {
    setCar(previousState => {
      return { ...previousState, color: "blue" }
    });
  }

  return (
    <>
      <h1>My {car.brand}</h1>
      <p>
        It is a {car.color} {car.model} from {car.year}.
      </p>
      <button
        type="button"
        onClick={updateColor}
      >Blue</button>
    </>
  )
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
const users = [
  { name: "user1", age: 28 },
  { name: "user2", age: 21 },
  { name: "user3", age: 38 },
  { name: "user4", age: 18 }
];

users.sort((user1, user2) => user1.age - user2.age);

console.log(users);
const repository = {
  id: 1,
  language: "javascript",
  public: true
};

for (const value of Object.values(repository)) {
  console.log(value);
}
const friends = [
  { name: "Abby", age: 22 },
  { name: "Boby", age: 16 },
  { name: "Coel", age: 20 },
  { name: "Dany", age: 15 }
];

//who can drink?
friends.filter(friend => friend.age >= 18);
const apps = ["phone", "calculator", "clock"];
const object = { ...apps };

console.log(object);
const person = {
  first_name: "Sam",
  last_name: "Bradley"
};

Object.values(person).includes("Bradley");
const person = {
  first_name: "Joan",
  last_name: "Leon",
  twitter: "@nucliweb"
};

Object.values(person)
  .toString()
  .includes("web");
const person = {
  key: "value",
  first_name: "John",
  last_name: "Doe"
};

Object.keys(person);
let name1={
  firstname: "Eloln", 
  lastname: "Musk",
  printFullName: function() {
    console.log(this.firstname + " " + this.lastname);
  }
}
let name1={
  firstname: "Eloln", 
  lastname: "Musk",
  printFullName: function() {
    console.log(this.firstname + " " + this.lastname);
  }
}

 
const getMessages = (status) => {
  // if(status === 'received'){
  //      return 'We are working on your order'
  // }else if(status === 'prepared'){
  //       return `Food is ready for collection`
  // }else if(status === 'onroute'){
  //       return `Your food is on its way`
  // }else if(status === 'arrived'){
  //   return `Your food has been delivered and signed for`
  // }else{
  //   return `unknown status`
  // }


  const messages = {
    received: 'We are working on your order',
    prepared: `Food is ready for collection`,
    onroute: `Your food is on its way`,
    arrived: `Your food has been delivered and signed for`
  }


  return messages[status] ?? 'unknown status'
}


const user = {
  name: 'David',
  status: 'arrived'
}


console.log(getMessages(user.status))
const person = {
 name: null,
    age: null,
    message: null,
}


<h3>{person?.name ?? 'default Name'}</h3>
<h3>{person?.age ?? 'default age'}</h3>
<h4>{person?.message ?? 'default message'}</h4>
const getMousePosition = (x, y) => ({
  x: x,
  y: y
});

//can be written as
const getMousePosition = (x, y) => ({ x, y });
const profileUpdate = (profileData) => {
  const { name, age, nationality, location } = profileData;

}
//This effectively destructures the object sent into the function. This can also be done in-place:

const profileUpdate = ({ name, age, nationality, location }) => {

}
//When profileData is passed to the above function, the values are destructured from the function parameter for use within the function.
const persons = [
  {firstname : "Malcom", lastname: "Reynolds"},
  {firstname : "Kaylee", lastname: "Frye"},
  {firstname : "Jayne", lastname: "Cobb"}
];

persons.map(getFullName);

function getFullName(item) {
  return [item.firstname,item.lastname].join(" ");
}
function getObjectDataByKey( field, theObject ){
	// get data
	return field.split('.').reduce((o,i)=> o[i], theObject);
}

// a simple object
const myObject = {
  name: 'John',
  lastname: 'Doe',
  data: {
    birthDate: '01/01/1970',
    placeOfBirth: 'San Francisco'
  }
}

// variable representing a key of the object
const field = 'data.birthDate';

console.log ( getObjectDataByKey ( field , myObject ) );
//will print
//01/01/1970

// also simple key will return correct value
console.log ( getObjectDataByKey ( 'name' , myObject) );
//will print
//John
function deepCopy(obj){
    let toString = Object.prototype.toString;
    if(typeof obj !== 'object') return obj;
    if(obj === null) return null;
    if(Array.isArray(obj)) return obj.map(deepCopy);
    let newObj = {};
    for(let key in obj){
        if(toString.call(obj[key])==='[object Date]'){
            newObj[key] = new Date(obj[key])
        } else if(toString.call(obj[key])==='[object RegExp]'){
            newObj[key] = new RegExp(obj[key])
        }else{
            newObj[key] = deepCopy(obj[key]);
        }
    }
    return newObj;
}
// Supported in IE 9-11
const people = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Adam'},
];

const isFound = people.some(element => {
  if (element.id === 1) {
    return true;
  }

  return false;
});

console.log(isFound); // 👉️ true

if (isFound) {
  // object is contained in array
}
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print  Object { name="John"}
const key1 = "name";
const key2 = "age";
const student = {
    [key1]:"john Doe",
    [key2]:26
}
console.log(student)
//{ name:"john Doe", age:26 }
const person = {
  name: 'Sam',
  age: 300,
}

const twinPerson = {
  ...person
}
// bad
function getFullName(user) {
  const firstName = user.firstName;
  const lastName = user.lastName;

  return `${firstName} ${lastName}`;
}

// good
function getFullName(user) {
  const { firstName, lastName } = user;
  return `${firstName} ${lastName}`;
}

// best
function getFullName({ firstName, lastName }) {
  return `${firstName} ${lastName}`;
}
function getKey(k) {
  return `a key named ${k}`;
}

// bad
const obj = {
  id: 5,
  name: 'San Francisco',
};
obj[getKey('enabled')] = true;

// good
const obj = {
  id: 5,
  name: 'San Francisco',
  [getKey('enabled')]: true,
};
cars.some(car => car.color === "red" && car.type === "cabrio");
// output: true

cars.every(car => car.capacity >= 4);
// output: false
let sortedCars = cars.sort((c1, c2) => (c1.capacity < c2.capacity) ? 1 : (c1.capacity > c2.capacity) ? -1 : 0);
console.log(sortedCars);
// output:
// [
//   {
//     color: 'purple',
//     type: 'minivan',
//     registration: 'Wed Feb 01 2017 00:00:00 GMT+0100 (GMT+01:00)',
//     capacity: 7
//   },
//   {
//     color: 'red',
//     type: 'station wagon',
//     registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
//     capacity: 5
//   },
//   ...
// ]
cars.forEach(car => {
 car['size'] = "large";
 if (car.capacity <= 5){
   car['size'] = "medium";
 }
 if (car.capacity <= 3){
   car['size'] = "small";
 }
});
cars.forEach(car => {
 car['size'] = "large";
 if (car.capacity <= 5){
   car['size'] = "medium";
 }
 if (car.capacity <= 3){
   car['size'] = "small";
 }
});
let sizes = cars.map(car => {
  if (car.capacity <= 3){
    return "small";
  }
  if (car.capacity <= 5){
    return "medium";
  }
  return "large";
});
console.log(sizes);
// output:
// ['large','medium','medium', ..., 'small']

//create a new object if we need more values:

let carsProperties = cars.map(car => {
 let properties = {
   "capacity": car.capacity,
   "size": "large"
 };
 if (car.capacity <= 5){
   properties['size'] = "medium";
 }
 if (car.capacity <= 3){
   properties['size'] = "small";
 }
 return properties;
});
console.log(carsProperties);
// output:
// [
//   { capacity: 7, size: 'large' },
//   { capacity: 5, size: 'medium' },
//   { capacity: 5, size: 'medium' },
//   { capacity: 2, size: 'small' },
//   ...
// ]
User Object Cheat Sheet
N

o matter what system you’re working in, it is always critical to be able to identify information about the user who is accessing that system. Being able to identify who the user is, what their groups and/or roles are, and what other attributes their user record has are all important pieces of information that allow you to provide that user with a good experience (without giving them information they don’t need to have or shouldn’t have). ServiceNow gives administrators some pretty simple ways to identify this information in the form of a couple of user objects and corresponding methods. This article describes the functions and methods you can use to get information about the users accessing your system.



GlideSystem User Object

The GlideSystem (gs) user object is designed to be used in any server-side JavaScript (Business rules, UI Actions, System security, etc.). The following table shows how to use this object and its corresponding functions and methods.

Function/Method	Return Value	Usage
gs.getUser()	Returns a reference to the user object for the currently logged-in user.	var userObject = gs.getUser();
gs.getUserByID()	Returns a reference to the user object for the user ID (or sys_id) provided.	var userObject = gs.getUser().getUserByID('employee');
gs.getUserName()	Returns the User ID (user_name) for the currently logged-in user.
e.g. 'employee'	var user_name = gs.getUserName();
gs.getUserDisplayName()	Returns the display value for the currently logged-in user.
e.g. 'Joe Employee'	var userDisplay = gs.getUserDisplayName();
gs.getUserID()	Returns the sys_id string value for the currently logged-in user.	var userID = gs.getUserID();
getFirstName()	Returns the first name of the currently logged-in user.	var firstName = gs.getUser().getFirstName();
getLastName()	Returns the last name of the currently logged-in user.	var lastName = gs.getUser().getLastName();
getEmail()	Returns the email address of the currently logged-in user.	var email = gs.getUser().getEmail();
getDepartmentID()	Returns the department sys_id of the currently logged-in user.	var deptID = gs.getUser().getDepartmentID();
getCompanyID()	Returns the company sys_id of the currently logged-in user.	var companyID = gs.getUser().getCompanyID();
getCompanyRecord()	Returns the company GlideRecord of the currently logged-in user.	var company = gs.getUser().getCompanyRecord();
getLanguage()	Returns the language of the currently logged-in user.	var language = gs.getUser().getLanguage();
getLocation()	Returns the location of the currently logged-in user.	var location = gs.getUser().getLocation();
getDomainID()	Returns the domain sys_id of the currently logged-in user (only used for instances using domain separation).	var domainID = gs.getUser().getDomainID();
getDomainDisplayValue()	Returns the domain display value of the currently logged-in user (only used for instances using domain separation).	var domainName = gs.getUser().getDomainDisplayValue();
getManagerID()	Returns the manager sys_id of the currently logged-in user.	var managerID = gs.getUser().getManagerID();
getMyGroups()	Returns a list of all groups that the currently logged-in user is a member of.	var groups = gs.getUser().getMyGroups();
isMemberOf()	Returns true if the user is a member of the given group, false otherwise.	Takes either a group sys_id or a group name as an argument.

if(gs.getUser().isMemberOf(current.assignment_group)){
//Do something...
}

var isMember = gs.getUser().isMemberOf('Hardware');

To do this for a user that isn't the currently logged-in user...

var user = 'admin';
var group = "Hardware";
if (gs.getUser().getUserByID(user).isMemberOf(group)){
gs.log( gr.user_name + " is a member of " + group);
}

else{
gs.log( gr.user_name + " is NOT a member of " + group);
}
gs.hasRole()	Returns true if the user has the given role, false otherwise.	if(gs.hasRole('itil')){ //Do something... }
gs.hasRole()	Returns true if the user has one of the given roles, false otherwise.	if(gs.hasRole('itil,admin')){
//If user has 'itil' OR 'admin' role then Do something...
}
hasRoles()	Returns true if the user has any roles at all, false if the user has no role (i.e. an ess user).	if(!gs.getUser().hasRoles()){
//User is an ess user...
}
It is also very simple to get user information even if the attribute you want to retrieve is not listed above by using a ‘gs.getUser().getRecord()’ call as shown here…

//This script gets the user's title
gs.getUser().getRecord().getValue('title');


g_user User Object

The g_user object can be used only in UI policies and Client scripts. Contrary to its naming, it is not truly a user object. g_user is actually just a handful of cached user properties that are accessible to client-side JavaScript. This eliminates the need for most GlideRecord queries from the client to get user information (which can incur a fairly significant performance hit if not used judiciously).

g_user Property or Method	Return value
g_user.userName	User name of the current user e.g. employee
g_user.firstName	First name of the current user e.g. Joe
g_user.lastName	Last name of the current user e.g. Employee
g_user.userID	sys_id of the current user e.g. 681ccaf9c0a8016400b98a06818d57c7
g_user.hasRole()	True if the current user has the role specified, false otherwise. ALWAYS returns true if the user has the 'admin' role.

Usage: g_user.hasRole('itil')
g_user.hasRoleExactly()	True if the current user has the exact role specified, false otherwise, regardless of 'admin' role.

Usage: g_user.hasRoleExactly('itil')
g_user.hasRoles()	True if the current user has at least one role specified, false otherwise.

Usage: g_user.hasRoles('itil','admin')
It is often necessary to determine if a user is a member of a given group from the client as well. Although there is no convenience method for determining this from the client, you can get the information by performing a GlideRecord query. Here’s an example…

//Check to see if assigned to is a member of selected group
var grpName = 'YOURGROUPNAMEHERE';
var usrID = g_form.userID; //Get current user ID
var grp = new GlideRecord('sys_user_grmember');
grp.addQuery('group.name', grpName);
grp.addQuery('user', usrID);
grp.query(groupMemberCallback);
   
function groupMemberCallback(grp){
//If user is a member of selected group
    if(grp.next()){
        //Do something
        alert('Is a member');
    }
    else{
        alert('Is not a member');
    }
}
To get any additional information about the currently logged-in user from a client-script or UI policy, you need to use a GlideRecord query. If at all possible, you should use a server-side technique described above since GlideRecord queries can have performance implications when initiated from a client script. For the situations where there’s no way around it, you could use a script similar to the one shown below to query from the client for more information about the currently logged in user.

//This script gets the user's title
var gr = new GlideRecord('sys_user');
gr.get(g_user.userID);
var title = gr.title;
alert(title);


Useful Scripts

There are quite a few documented examples of some common uses of these script methods. These scripts can be found on the ServiceNow wiki.
const myObject= {
  'Age': '25',
  'Gender': 'Male',
  'Nationality': 'Australian'
};

const myMap = new Map(Object.entries(myObject)); //object to map
const anotherObject = Object.fromEntries(myMap) // map to object
star

Tue Oct 31 2023 09:27:32 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/react_usestate.asp

#react.js #usestate #object #update
star

Wed Apr 05 2023 22:21:51 GMT+0000 (Coordinated Universal Time) https://codetogo.io/how-to-sort-array-of-objects-in-ascending-order-in-javascript/

#javascript #array #object #sort #order
star

Wed Apr 05 2023 22:18:46 GMT+0000 (Coordinated Universal Time) https://codetogo.io/how-to-loop-through-object-in-javascript/

#javascript #loop #object
star

Wed Apr 05 2023 22:14:21 GMT+0000 (Coordinated Universal Time) https://codetogo.io/how-to-filter-objects-in-array-in-javascript/

#javascript #array #filter #object
star

Wed Apr 05 2023 16:08:37 GMT+0000 (Coordinated Universal Time) https://codetogo.io/how-to-create-object-from-array-in-javascript/

#javascript #object #transform #array
star

Wed Apr 05 2023 16:04:34 GMT+0000 (Coordinated Universal Time) https://codetogo.io/how-to-check-if-object-includes-value-in-javascript/

#javascript #object #value #validate
star

Wed Apr 05 2023 16:03:47 GMT+0000 (Coordinated Universal Time) https://codetogo.io/how-to-check-if-object-includes-substring-in-javascript/

#javascript #object #validate #if #string
star

Wed Apr 05 2023 15:59:14 GMT+0000 (Coordinated Universal Time) https://codetogo.io/

#javascript #keys #object
star

Sat Dec 24 2022 04:36:46 GMT+0000 (Coordinated Universal Time)

#object #javascript
star

Sat Dec 24 2022 04:36:46 GMT+0000 (Coordinated Universal Time)

#object #javascript
star

Wed Dec 21 2022 03:37:57 GMT+0000 (Coordinated Universal Time)

#dynamic #advanced-flow #object
star

Sat Oct 15 2022 05:11:36 GMT+0000 (Coordinated Universal Time)

#javascript #nullish #object
star

Tue Jul 12 2022 09:37:40 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-object-property-shorthand

#array #object #destructure #parameter #arrowfunction
star

Tue Jul 12 2022 09:23:55 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters

#array #object #destructure #parameter #arrowfunction
star

Tue Jul 12 2022 05:31:55 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/jsref/jsref_map.asp

#array #object #map #join
star

Sun Jun 19 2022 04:40:24 GMT+0000 (Coordinated Universal Time)

#javascript #object #deep #copy #clone #recursion
star

Sat Feb 12 2022 20:24:31 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable

#javascript #object #key
star

Wed Dec 01 2021 17:05:39 GMT+0000 (Coordinated Universal Time) https://medium.com/@abhinav_vp/another-4-javascript-tips-for-shorter-code-64791c1111b4

#object #javascript
star

Mon Nov 15 2021 15:49:41 GMT+0000 (Coordinated Universal Time) https://medium.com/@giuliamalaroda/7-javascript-functions-to-master-objects-manipulation-and-make-your-code-cleaner-cc142a269b13

#javascript #object #functions
star

Tue Oct 12 2021 13:32:02 GMT+0000 (Coordinated Universal Time)

#javascript #spread #object #oop
star

Thu Aug 19 2021 17:06:40 GMT+0000 (Coordinated Universal Time) https://github.com/airbnb/javascript

#object #destructuring
star

Thu Aug 19 2021 15:53:29 GMT+0000 (Coordinated Universal Time) https://github.com/airbnb/javascript

#object #literals
star

Tue Jun 29 2021 11:46:34 GMT+0000 (Coordinated Universal Time)

#object #array #javascript #vanilla
star

Tue Jun 29 2021 11:46:09 GMT+0000 (Coordinated Universal Time)

#object #array #javascript #vanilla
star

Tue Jun 29 2021 11:45:24 GMT+0000 (Coordinated Universal Time)

#object #array #javascript #vanilla
star

Fri Dec 11 2020 17:35:23 GMT+0000 (Coordinated Universal Time) https://servicenowguru.com/scripting/user-object-cheat-sheet/

#servicenow #user #object
star

Tue Nov 24 2020 12:48:26 GMT+0000 (Coordinated Universal Time) https://medium.com/javascript-in-plain-english/stop-using-objects-and-arrays-to-store-data-289c3edaaa33

#javascript #object #map

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension