DEV Community

Zen
Zen

Posted on

CRUD in JSON

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

Top comments (1)

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman • Edited
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