• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

202
Views
Creación de objetos utilizando elementos de matriz sin sobrescribir claves existentes

Intento crear un objeto a partir de una matriz que contiene muchas matrices. Los elementos de la matriz deben ser claves de objeto anidadas entre sí, solo si la clave no se ha creado inicialmente. Es decir, no debe sobrescribir la clave y también debe mantener el índice de clave.

Ejemplo es este -

 const MainArray = [ { key: ['name', 'dog', 'feature', 'hairy'], value1:1 , value2:2 }, { key: ['name', 'dog', 'eye', 'brown'], value1:1 , value2:2 }, { key: ['kind', 'human', 'class', 'man', 'height', 'tall'], value1:'Mike' , value2:'John' }, { key: ['kind', 'human', 'class', 'woman', 'hobby'], value1:'Cyling' , value2:'Tennis' }, ] const requiredObject = { name:{ dog :{ feature:{ hairy :{value1:1, value2:2} }, eye:{ brown:{value1:1, value2:2} } } }, kind:{ human:{ class:{ man:{ height:{ tall:{value1:'Mike', value2:'John'} } }, woman:{ hobby:{value1:'Cyling', value2: 'Tennis'} } } } } }

¿Cómo puedo pasar de MainArray a requireObject

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede usar array.reduce() para construir un nuevo objeto recorriendo matrices key usando otro array.reduce() . Probar:

 const MainArray = [ { key: ['name', 'dog', 'feature', 'hairy'], value1:1 , value2:2 }, { key: ['name', 'dog', 'eye', 'brown'], value1:1 , value2:2 }, { key: ['kind', 'human', 'class', 'man', 'height', 'tall'], value1:'Mike' , value2:'John' }, { key: ['kind', 'human', 'class', 'woman', 'hobby'], value1:'Cyling' , value2:'Tennis' } ]; const result = MainArray.reduce((acc, cur) => { let { key, ...data } = cur; let lastIndex = key.length - 1; key.reduce((obj, k, index) => { obj[k] = obj[k] || (index === lastIndex ? {...data} : {}); return obj[k]; }, acc); return acc; }, {}); console.log(result);

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error