DEV Community

loading...

CRUD in JSON

mzaini30 profile image Zen ・1 min read
data = [
 {
  "id": 0.63773,
  "nama": "Zen",
  "asal": "Samarinda"
 },
 {
  "id": 0.5262,
  "nama": "Yogi",
  "asal": "Loa Janan"
 }
]

// create
// tambah data

data.push({
 id: Math.random(),
 nama: "Maryam",
 asal: "Buah hati"
})

// read
// ambil data tertentu

x = data.filter(x => x.id == 0.5262)

// update

n = data.findIndex(x => x.id == 0.5262)
data[n].nama = "Anggi"

// delete

x = data.filter(x => x.id != 0.5262)
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide
Collapse
taufik_nurrohman profile image
Taufik Nurrohman
let data = {};
let id = Math.random();

// Create if not exists (primary key as object key)
!data[id] && (data[id] = {
    "nama": "Taufik",
    "asal": "?"
});

// Read
console.log(data[id] || {
    "nama": null,
    "asal": null
});

// Update
data[id] && Object.assign(data[id], {
    "nama": "Nur"
});

// Delete
delete data[id];
Enter fullscreen mode Exit fullscreen mode