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

109
Views
JS - Empujar elementos condicionalmente en objeto anidado

Tengo esta matriz:

 let mainArray = [ { "key1": "value1" // <------------ }, // | { // | "key2": "value2" // | key1 exists two times }, // | { // | "key1": "toAddValue" // <------------ } ];

Rendimiento esperado:

El valor de Key1 debe estar en una matriz única

 [ { 'item': { 'data': ['value1', 'toAddValue'], // <-- It's values should be in Single arr 'path': 'key1' // <-- It's key name in path field. } }, { 'item': { 'data': ['value2'], // <-- its' value occurs once 'path': 'key2' // <-- so it should be in one array. } } ]

Pregunta:

Si alguna de las claves de mainArray vuelve a ocurrir / se repite, entonces, debe agregarse a una matriz única llamada datos

¿Cómo hago esto?

 var secondArray = []; // New array where all outputs are collected let mainArray = [{ "key1": "value1" }, { "key2": "value2" }, { "key1": "newKeyVal" } ]; for (let i = 0; i <= mainArray.length; i++) { for (let j = 0; j <= secondArray.length; j++) { if (secondArray.length == 0) { secondArray.push({ "item": { 'data': [Object.values(i)[0]], 'path': `${Object.keys(i)[0]}` } }) } if (secondArray[j].item.path === Object.keys(i)[0]) { secondArray[j].item.data.push([Object.values(i)[0]]) } } } console.log(secondaryArray)

about 4 years ago · Juan Pablo Isaza
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!