-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2675-array-of-objects-to-matrix.js
59 lines (53 loc) · 1.29 KB
/
2675-array-of-objects-to-matrix.js
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
var jsonToMatrix = function (arr) {
// hashset
const keySet = new Set();
// used 'of' coz we want actual object in arr not index
for (const obj of arr) {
getKeys(obj, '');
}
const keys = Array.from(keySet).sort();
const result = [keys]; // array of keys -first row
// for second and subsequent rows - values arr
for (const obj of arr) {
const keyToVal = {};
getValues(obj, '', keyToVal);
let row = [];
for (const key of keys) {
if (key in keyToVal) {
row.push(keyToVal[key]);
} else {
row.push('');
}
}
result.push(row);
}
return result;
// function to get keys
function getKeys(obj, path) {
for (const key in obj) {
const newPath = path ? `${path}.${key}` : key;
// key is object
if (isObject(obj[key])) {
getKeys(obj[key], newPath);
}
// not an object
else {
keySet.add(newPath);
}
}
}
//
function getValues(obj, path, keyToVal) {
for (const key in obj) {
const newPath = path ? `${path}.${key}` : key;
if (isObject(obj[key])) {
getValues(obj[key], newPath, keyToVal);
} else {
keyToVal[newPath] = obj[key];
}
}
}
function isObject(obj) {
return obj !== null && typeof obj === 'object';
}
};