hola tengo este codigo
let key = N001DSC29MC22HC22DD04MD09YD21 function get(key) { let res = {}; res.matchNumber = key.match(/(?<=N)\d{3}/g); res.matchSeconds = key.match(/(?<=DSC)\d{2}/g); res.matchMinutes = key.match(/(?<=MC)\d{2}/g); res.matchHours = key.match(/(?<=HC)\d{2}/g); res.matchDay = key.match(/(?<=DD)\d{2}/g); res.matchMonth = key.match(/(?<=MD)\d{2}/g); res.matchYear = key.match(/(?<=YD)\d{2}/g); res.title = JSON.parse(localStorage.getItem(key)).title; res.description = JSON.parse(localStorage.getItem(key)).description; Object.keys(res).forEach(key => { if (! res[key]) delete res[key] if (Array.isArray(res[key])) res[key] = res[key].join('') }) return res; } get(key)Como puede ver, mi código no está limpio, hay una mejor manera de hacer la misma función. Realmente lo intento y no puedo hacerlo mejor
Quiero decir que es mejor usar REGEXP y hacer match muy papilla Me gusta esto
En mi opinión, puede poner la inicialización de los campos del objeto en línea con la creación del objeto, y foreach no es el mejor para hacer efectos secundarios, intente hacer que el objeto sea const y use algo como filtrar y reducir:
// the snipped won't work because of the sandbox policy let key = 'N001DSC29MC22HC22DD04MD09YD21'; function get(key) { const res = { matchNumber : key.match(/(?<=N)\d{3}/g), matchSeconds : key.match(/(?<=DSC)\d{2}/g), matchMinutes : key.match(/(?<=MC)\d{2}/g), matchHours : key.match(/(?<=HC)\d{2}/g), matchDay : key.match(/(?<=DD)\d{2}/g), matchMonth : key.match(/(?<=MD)\d{2}/g), matchYear : key.match(/(?<=YD)\d{2}/g), title : JSON.parse(localStorage.getItem(key)).title, description : JSON.parse(localStorage.getItem(key)).description, }; return Object.entries(res) .filter(([k]) => k) .reduce((acc, [k,v]) => (acc[k] = v, acc), {}) } get(key) Sin embargo, en realidad puede evitar crear el objeto res y comenzar con otra estructura de datos (la que Object.entries )
let key = 'N001DSC29MC22HC22DD04MD09YD21'; function get(key) { return [ ['matchNumber' , key.match(/(?<=N)\d{3}/g)], ['matchSeconds' , key.match(/(?<=DSC)\d{2}/g)], ['matchMinutes' , key.match(/(?<=MC)\d{2}/g)], ['matchHours' , key.match(/(?<=HC)\d{2}/g)], ['matchDay' , key.match(/(?<=DD)\d{2}/g)], ['matchMonth' , key.match(/(?<=MD)\d{2}/g)], ['matchYear' , key.match(/(?<=YD)\d{2}/g)], ['title' , JSON.parse(localStorage.getItem(key)).title], ['description' , JSON.parse(localStorage.getItem(key)).description], ].filter(([k]) => k).reduce((acc, [k,v]) => (acc[k] = v, acc), {}) } get(key)Crear un objeto usando Object.fromEntries , donde las entradas se filtran y asignan desde Object.entries se ve un poco más limpio.
console.log(get(`N001DSC29MC22HC22DD04MD09YD21`)); function get(key) { return Object.fromEntries( Object.entries({ matchNumber: key.match(/(?<=N)\d{3}/g), matchSeconds: key.match(/(?<=DSC)\d{2}/g), matchMinutes: key.match(/(?<=MC)\d{2}/g), matchHours: key.match(/(?<=HC)\d{2}/g), matchDay: key.match(/(?<=DD)\d{2}/g), matchMonth: key.match(/(?<=MD)\d{2}/g), matchYear: key.match(/(?<=YD)\d{2}/g), // mockup for not working localStorage in sandbox title: `sometitle`, description: `somedescription`, }) // filter only key-value pairs with a value .filter( ([key, value]) => value ) // map to values with joined Arrays if applic. .map( ([key, value]) => [key, Array.isArray(value) ? value.join('') : value ] ) ); }Alternativa, etiquetas y expresiones regulares de una cadena sin procesar , usando un reductor para crear el objeto.
const getValuesFromKey = key => ({ ...String.raw` ID::(?<=N)\d{3} Seconds::(?<=DSC)\d{2} Minutes::(?<=MC)\d{2} Hours::(?<=HC)\d{2} Day::(?<=DD)\d{2} Month::(?<=MD)\d{2} NoMatch::(?<=NOTHING)\d{2} // won't match anything Years::(?<=YD)\d{2} // will find two years ` .split(`\n`) .reduce( (acc, line) => { line = line.replace(/\/\/.*$/, ``).trim(); const [label, re] = line && line.split(`::`); const match = re && key.match(new RegExp(re, `g`)); return match ? {...acc, [[label]]: match.join(` and `)} : acc; }, {}), Title: `someTitle`, Description: `someDescription` }); console.log(getValuesFromKey(`N001DSC29MC22HC22DD04MD09YD21YD45`)); // ^ extra valueO utilice grupos de captura con nombre . Ver este proyecto de stackblitz