Tengo la siguiente matriz:
[ ["Polymeric", "Vehicle Graphics (Basic)"], ["Cast", "Vehicle Graphics (Part Wrap), Vehicle Graphics (Full Wrap)"], ["Polymeric", "Vehicle Graphics (Part Wrap)"] ]Necesito este:
[ ["Polymeric", "Vehicle Graphics (Basic)"], ["Cast", "Vehicle Graphics (Part Wrap)"], ["Cast", "Vehicle Graphics (Full Wrap)"], ["Polymeric", "Vehicle Graphics (Part Wrap)"] ]Aquí está mi código:
const source = [ ["Polymeric", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Basic)"], ["Cast", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Part Wrap), Vehicle Graphics (Full Wrap)"], ["Polymeric", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Part Wrap)"] ]; source.flatMap(([key, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10, value11, value12, value13, value14, value15, value16]) => { const values = value16.split(', ') var hjk = values.map(singleValue => [key, singleValue]) console.log(hjk); })Aquí hay un jsfiddle de su funcionamiento.
¿Hay una mejor manera de hacer esto? Poner valor1, valor2, etc. parece una tontería.
Podría desestructurar los valores deseados y mapear los pares deseados.
const source = [["Polymeric", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Basic)"], ["Cast", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Part Wrap), Vehicle Graphics (Full Wrap)"], ["Polymeric", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Part Wrap)"]], result = source.flatMap(({ 0: key, 16: values }) => values .split(', ') .map(value => [key, value]) ); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }Podrías hacer esto:
const source = [ ["Polymeric", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Basic)"], ["Cast", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Part Wrap), Vehicle Graphics (Full Wrap)"], ["Polymeric", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Part Wrap)"] ]; source.flatMap((arr) => { let [key] = arr; let value16 = arr[16]; const values = value16.split(', ') var hjk = values.map(singleValue => [key, singleValue]) console.log(hjk); })