Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
¿Cómo debo crear un objeto que almacene ID con sub ID sin usar matrices?

Necesito enviar datos al servidor que tiene varias identificaciones con subidentificaciones. Actualmente estoy usando arreglos, pero debido a que necesito manejar cada id y sub id en el dom (actualmente con vue), uso mucho find() y findIndex() una y otra vez. Si hay una manera de usar las identificaciones directamente, solo podría acceder o verificarlas con order[id][subid].

Actualmente estoy usando esta estructura:

 let data = { orders: [ { order_id: 4, items: [{ item_id: 6 }, { item_id: 7 }, { item_id: 8 }] }, { order_id: 1, items: [{ item_id: 1 }, { item_id: 2 }, { item_id: 3 }] }, ]; }

Aquí, cuando, por ejemplo, quiero que verifique si un artículo de pedidos está marcado, tengo que

 function check(order_id, item_id) { let order_i = data.orders.findIndex((o) => o.order_id == order_id); if (order_i != -1) { let item_i = data.orders[order_i].items.findIndex((o) => o.item_id == item_id); } if (item_i != -1) { return true; } else { return false; } }

o algo así. Cómo quiero usarlo

 let data = { orders: { 4: {6:'',7:'',8:''}, 1: {1:'',2:'',3:''} } }

y luego simplemente usaría data.orders?.[order_id]?.[item_id]

No estoy seguro de que sea un buen enfoque. No parece tan ¿Qué estructura podría usar para esto, sin usar matrices?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Creo que la estructura de datos que desea es el Mapa. Almacena pares clave-valor y puede recuperar el valor de una clave específica en tiempo constante (en lugar de buscar en toda la lista). Los métodos set(key, value) y get(key) son para interactuar con el objeto Map.

Si todos los pedidos se almacenan en esta estructura, debe usar la identificación como índice en una matriz, eso sería lo más eficiente. Puede usar un Mapa para los pedidos si no son secuenciales (no todas las identificaciones están presentes) y otro Mapa para los artículos. Si en promedio no hay muchos elementos en un orden dado, entonces usar un Array para eso debería estar bien.

Lea más: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

about 4 years ago · Santiago Trujillo Report

0

A continuación se presenta una posible forma de lograr el objetivo deseado.

Fragmento de código

 // methoed to transform data into desired format const transformMyData = obj => ({ orders: obj?.orders?.reduce( // iterate using ".reduce()" for orders (acc, {order_id, items, ...rest1}) => ( // transform each array-elt into prop-value format acc[order_id] ??= {}, acc[order_id] = {...rest1}, acc[order_id].items = items.reduce( // iterate items (ac2, {item_id, ...rest2}) => ( // transform into prop-value format ac2[item_id] ??= {}, ac2[item_id] = {...rest2}, ac2 ), {} // this may be replaced with new Map() to use map instead of object ), acc ), {} // this may be replaced with new Map() to use map instead of object ) }); // NOTE: If using "new Map()", please use ".get()" and ".set()" to access & set-up/update. const data = { orders: [{ order_id: 4, otherOrderProps: 'otherOrderValues1', items: [{ item_id: 6, otherItemProps: 'a6' }, { item_id: 7, otherItemProps: 'a7' }, { item_id: 8, otherItemProps: 'a8' }] }, { order_id: 1, otherOrderProps: 'otherOrderValues2', items: [{ item_id: 1, otherItemProps: 'a1' }, { item_id: 2, otherItemProps: 'a2' }, { item_id: 3, otherItemProps: 'a3' }] }] }; console.log('transformed data:\n', transformMyData(data)); console.log( '\n\ncheck for order: 1, item: 2\n', transformMyData(data)?.orders?.[1]?.items?.[2] ?? 'not-found' ); console.log( '\n\ncheck for non-existent order: 3, item: 2\n', transformMyData(data)?.orders?.[3]?.items?.[2] ?? 'not-found' );
 .as-console-wrapper { max-height: 100% !important; top: 0 }

Explicación

Se agregaron comentarios en línea al fragmento anterior.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!