Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

354
Visualizações
¿Cómo acceder, fusionar y recopilar valores de matriz dentro de una estructura de datos anidados según diferentes criterios?

Tengo debajo de la matriz de objetos. Como puede ver, tengo 2 runTypes llamados VEGGIES y FRUITS . Cada tipo de runType tendrá una lista de verticales. Por ejemplo, VEGGIES tiene SPINACH, TOMATO, ONION y FRUTAS tiene APPLE, BANANA, GRAPES

 let data = [ { "runType": "VEGGIES", "verticals": [ { "vertical": "SPINACH", "radars": {} }, { "vertical": "TOMATO", "radars": {} }, { "vertical": "ONION", "radars": {} }, ], "total_count": {} }, { "runType": "FRUITS", "verticals": [ { "vertical": "APPLE", "radars": { } }, { "vertical": "BANANA", "radars": {} }, { "vertical": "GRAPES", "radars": { "P5": 8 } } ], "total_count": { "P5": 8 } } ]

En mi caso, quiero extraer estos valores vertical y ponerlos en una matriz. En el caso de una matriz regular de objetos, podemos lograr la tarea anterior usando este código.

 let result = data.map(({ verticals }) => vertical)

Pero mi código tiene una matriz de objetos dentro de una matriz de objetos. ¿Puede alguien decirme cómo lograr estos 3 escenarios?

  1. Escenario 1: obtenga todas las verticales para ambos tipos de ejecución. El resultado debe ser [ESPINAS, TOMATE, CEBOLLA, MANZANA, PLÁTANO, UVAS]
  2. Escenario 2: obtenga todas las verticales para runType = 'VEGGIES'. El resultado debe ser [ESPINAS, TOMATE, CEBOLLA]
  3. Escenario 3: obtenga todas las verticales para runType = 'FRUITS'. El resultado debería ser [MANZANA, PLÁTANO, UVAS]

¿Alguien puede arrojar algo de luz sobre estos datos en particular?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Además del map el OP también podría echar un vistazo a flatMap y find ... reduce también vale la pena intentarlo ...

 let data = [{ "runType": "VEGGIES", "verticals": [{ "vertical": "SPINACH", "radars": {}, }, { "vertical": "TOMATO", "radars": {}, }, { "vertical": "ONION", "radars": {}, }], "total_count": {}, }, { "runType": "FRUITS", "verticals": [{ "vertical": "APPLE", "radars": {}, }, { "vertical": "BANANA", "radars": {}, }, { "vertical": "GRAPES", "radars": { "P5": 8, }, }], "total_count": { "P5": 8, }, }]; // Scenario 1 // - Get all the verticals for both runType. // - Result should be [SPINACH, TOMATO, ONION, APPLE, BANANA, GRAPES] console.log('Scenario 1 ... ', data .flatMap(({ verticals }) => verticals.map(({ vertical }) => vertical) ) ); // Scenario 2 // - get all verticals for runType = 'VEGGIES'. // - Result should be [SPINACH, TOMATO, ONION] console.log('Scenario 2 ... ', data .find(item => item.runType === 'VEGGIES') .verticals.map(({ vertical }) => vertical) ); // Scenario 3 // - get all verticals for runType = 'FRUITS'. // - Result should be [APPLE, BANANA, GRAPES] console.log('Scenario 3 ... ', data .find(item => item.runType === 'FRUITS') .verticals.map(({ vertical }) => vertical) ); // Bonus // - based on Array#reduce one can achieve everything at once function groupMergeAndCollectVerticals(collector, item) { const { index, list } = collector; const { runType, verticals } = item; const group = (index[runType] ??= []); const verticalList = verticals.map(({ vertical }) => vertical); group.push(...verticalList); list.push(...verticalList); return collector; } const verticalsCollection = data.reduce(groupMergeAndCollectVerticals, { index: {}, list: [] }); console.log( 'reduce based :: all at once ... ', verticalsCollection ); console.log( 'reduce based :: Scenario 1 ... ', verticalsCollection.list ); console.log( 'reduce based :: Scenario 2 ... ', verticalsCollection.index['VEGGIES'] ); console.log( 'reduce based :: Scenario 3 ... ', verticalsCollection.index['FRUITS'] );
 .as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

Prueba esto:

 let data = [{ "runType": "VEGGIES", "verticals": [{ "vertical": "SPINACH", "radars": {} }, { "vertical": "TOMATO", "radars": {} }, { "vertical": "ONION", "radars": {} }, ], "total_count": {} }, { "runType": "FRUITS", "verticals": [{ "vertical": "APPLE", "radars": { } }, { "vertical": "BANANA", "radars": {} }, { "vertical": "GRAPES", "radars": { "P5": 8 } } ], "total_count": { "P5": 8 } } ] var findData = (runType) => data.filter(x => x.runType == runType).map(x => x.verticals)[0].map(i => i.vertical) console.log("VEGGIES:", findData("VEGGIES")) console.log("FRUITS:", findData("FRUITS")) console.log("COMBINED:", findData("VEGGIES").concat(findData("FRUITS")))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda