Quiero crear un objeto de matrices, pero cuando ejecuto el siguiente código, me da
TypeError: Cannot read property 'push' of undefined
¿Cómo puedo empujar algo a una matriz no existente?
const obj = {} someArray.forEach(key => { anotherArray.forEach(key2 => { obj[key].push(key2) }) })Aquí obj es una matriz vacía, no tiene propiedad key . Entonces, antes de presionar, puede verificar si tiene la propiedad, si no, puede crear y luego push
const obj = {} someArray.forEach(key => { anotherArray.forEach(key2 => { if (!obj[key]) { obj[key] = [] } obj[key].push(key2) }) })