mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
problems(js): add “2675. Array of Objects to Matrix”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
060090921d
commit
f2bbcdd10a
1 changed files with 49 additions and 0 deletions
49
problems/js/array-of-objects-to-matrix.js
Normal file
49
problems/js/array-of-objects-to-matrix.js
Normal file
|
@ -0,0 +1,49 @@
|
|||
const isObject = x => x !== null && typeof x === 'object';
|
||||
|
||||
const getKeys = object => {
|
||||
if (!isObject(object)) {
|
||||
return [''];
|
||||
}
|
||||
|
||||
let result = [];
|
||||
|
||||
Object.keys(object).forEach(key => {
|
||||
getKeys(object[key]).forEach(subKey => {
|
||||
result.push(subKey ? `${key}.${subKey}` : key);
|
||||
});
|
||||
});
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const getValue = (obj, path) => {
|
||||
let [value, i, paths] = [obj, 0, path.split('.')];
|
||||
for (i = 0; i < paths.length && isObject(value); ++i) {
|
||||
value = value[paths[i]];
|
||||
}
|
||||
|
||||
if (i < paths.length || value === undefined || isObject(value)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {Array} arr
|
||||
* @return {Matrix}
|
||||
*/
|
||||
const jsonToMatrix = function(arr) {
|
||||
let keySet = arr.reduce((keys, key) => {
|
||||
getKeys(key).forEach(k => keys.add(k));
|
||||
return keys;
|
||||
}, new Set());
|
||||
|
||||
let keys = Array.from(keySet).sort();
|
||||
|
||||
let matrix = [keys];
|
||||
arr.forEach(obj => {
|
||||
matrix.push(keys.map(key => getValue(obj, key)));
|
||||
});
|
||||
return matrix;
|
||||
};
|
Loading…
Reference in a new issue