-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
85 lines (70 loc) · 1.71 KB
/
index.js
File metadata and controls
85 lines (70 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
export function findNestedObjectById(objects, id) {
if (objects === null || typeof objects !== 'object') {
return null
}
if (objects.id === id || objects['@id'] === id) {
return objects
}
if (Array.isArray(objects)) {
for (const obj of objects) {
const result = findNestedObjectById(obj, id)
if (result) {
return result
}
}
} else {
for (const key in objects) {
const child = objects[key]
if (typeof child === 'object' || Array.isArray(child)) {
const result = findNestedObjectById(child, id)
if (result) {
return result
}
}
}
}
return null
}
export function create(objects, id, data) {
objects[id] = { ...data }
return objects[id]
}
export function fetch(objects, id) {
return findNestedObjectById(objects, id) || null
}
export function update(objects, id, data) {
const targetObject = findNestedObjectById(objects, id)
if (!targetObject) {
return null
}
Object.assign(targetObject, data)
return targetObject
}
export function deleteObject(objects, id) {
if (objects[id]) {
delete objects[id]
return true
}
for (const key in objects) {
if (typeof objects[key] === 'object') {
const result = deleteObject(objects[key], id)
if (result) {
return true
}
}
}
return false
}
export function importJSON(objects, json) {
const inputData = JSON.parse(json)
inputData.forEach((item) => {
const { '@id': id, ...data } = item
create(objects, id, data)
})
}
export function exportJSON(objects) {
const outputData = Object.keys(objects).map((id) => {
return { '@id': id, ...objects[id] }
})
return JSON.stringify(outputData, null, 2)
}