Skip to main content

2675. Array of Objects to Matrix

https://leetcode.com/problems/array-of-objects-to-matrix

Javascript

const extract = (item, key='', result=[]) => {
if ( typeof item === 'number'
|| typeof item === 'string'
|| typeof item === 'boolean'
|| item === null) {
return {[key]: item}
}

for (const [k, v] of Object.entries(item)) {
const newKey = key === '' ? k : `${key}.${k}`
result.push(extract(v, newKey))
}
return result.flat()
}

var jsonToMatrix = function(arr) {
const mapper = arr.map(item => extract(item))
const keys = Array.from(new Set(mapper.flat().map(item => Object.keys(item)[0])))
keys.sort()

const result = [keys]
for (const items of mapper) {
const current = []
for (const key of keys) {
const value = items.find((item) => item.hasOwnProperty(key))?.[key]
current.push(value === undefined ? '' : value)
}
result.push(current)
}

return result
};