Tuesday, December 17, 2019

Useful JavaScript Snippets

By using lodash you can loop through arrays and objects with ease

const _ = require("lodash");
// replace object in array
var arr = [{ id: 1, name: "Adam" }, { id: 2, name: "Bob" }];
var index = _.findIndex(arr, { id: 1 });
arr.splice(index, 1, { id: 100, name: "New man" });
document.write(JSON.stringify(arr));
document.write(`<hr/>`);
// update object in array
var mike = { id: 17, name: "mike" };
var newMike = { id: 17, name: "New Mike" };
var updatedMike = _.merge(mike, newMike);
document.write(JSON.stringify(updatedMike));
document.write(`<hr/>`);
// iterate over object using key value
const obj = { a: [76, 23], b: ["en", "es"]}
const result = _.map(obj, (value, key) => {
  document.write(`pair: ${key} : ${value[0]} <br />`);
});
document.write(`<hr/>`);
// filter array of objects by property 
var users = [
  { 'user': 'Adam', 'age': 36, 'active': false },
  { 'user': 'Bob', 'age': 40, 'active': false }
];
var flint = _.filter(users, o => o.age === 40)
document.write(JSON.stringify(flint));
Dealing with undefined in ternary operator

let element;
let item = typeof element === 'undefined' ? 'no val' : element;
  
console.log(item) // no val

Adding an element to a object
    let item = {id: 119 ,name: 'clothing', amount: 45}
 
    // no mutation add at the end of element
    let newItem1 = Object.assign({}, item, {category: 'Personal'})
    console.log(item);
    console.log(newItem1);
 
    // mutate add to end of element
    item = Object.assign(item, {category: 'Personal'});
    console.log(item);
 
    // proces array add at the end of every element
    let collection: any[] = []
    let items = [
      {id: 119 ,name: 'clothing', amount: 45},
      {id: 118 ,name: 'umbrela', amount: 47}
    ]
 
    items.map((item) => collection.push({...item, key4:"val4"}))
    console.log(collection);
Clone and modify existing element in clone. Great for setState in react.
const arrayOfObjects = [
  {name:"adam", isChecked: false},
  {name:"bob", isChecked: false}
]
 
let clone = arrayOfObjects.map((item) => ({...item}));
 
clone.map((item) => item.isChecked = true)
 
clone.map((item)=> console.log("clone ",item.name, item.isChecked))
arrayOfObjects.map((item)=> console.log("arrayOfObjects ",item.name, item.isChecked))

No comments:

Post a Comment