localstorage array of objects code example

Example 1: set array of objects in localstorage

//set item in local storage
localStorage.setItem("savedData", JSON.stringify(objects));

//retrieve item from local storage
objects = JSON.parse(localStorage.getItem("savedData")));

Example 2: array of objects javascript

var widgetTemplats = [
    {
        name: 'compass',
        LocX: 35,
        LocY: 312
    },
    {
        name: 'another',
        LocX: 52,
        LocY: 32
    }
]

Example 3: typescript array of objects

//Define an interface to standardize and reuse your object
interface Product {
    name: string;
    price: number;
    description: string;
}

let pen: Product = {
  name: "Pen",
  price: 1.43,
  description: "Userful for writing"
}

let products: Product[] = [];
products.push(pen);
//...do other products.push(_) to add more objects...
console.log(products);
/* -->
*[
* {
*  name: "Pen",
*  price: 1.43,
*  description: "Userful for writing"
* },
* ...other objects...
*]

Example 4: how push objects into a local stotage array

// Get the existing data
var existing = localStorage.getItem('myFavoriteSandwich');

// If no existing data, create an array
// Otherwise, convert the localStorage string to an array
existing = existing ? existing.split(',') : [];

// Add new data to localStorage Array
existing.push('tuna');

// Save back to localStorage
localStorage.setItem('myFavoriteSandwich', existing.toString());