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

0

195
Views
Empujando Nuevo valor a Array of Objects mientras se mantiene intacto el antiguo React Js Next Js

Tengo un archivo JSON con nombres de imagen. Quiero almacenar datos en un objeto de valor clave. Estoy creando la clave usando expresiones regulares para eliminar -img[image No] . No puedo almacenar todos los nombres de imágenes en la matriz. Cuando agrego un nuevo elemento, lo sobrescribe al valor anterior.

¿Cómo puedo insertar nuevos datos en una matriz sin borrar los datos almacenados previamente?

Documento de datos

 [ "apple-img1", "apple-img2", "apple-img3", "apple-img4", "apple-img5", "dell-img1", "dell-img2", "dell-img3", "hp-img1", "hp-img2" ]

Mi código

 content.map((contentInfo) => { let key = contentInfo.replace(/-img\d$/, "") //Return Company Name without -i{Digit} For Example apple-img1 whould be apple let imgName = contentInfo //Name of the Image data[key] = { Images: imgName //Append New Image 2 Array Instead of OverWriting Them } console.log(data); })

Salida de corriente

 { "apple": { "Images": [ "apple-img5" ] }, "dell": { "Images": [ "dell-img3" ] }, "hp": { "Images": [ "hp-img2" ] } }

Rendimiento esperado

 { "apple": { "Images": [ "apple-img1", "apple-img2", "apple-img3", "apple-img4", "apple-img5" ] }, "dell": { "Images": [ "dell-img1", "dell-img2", "dell-img3" ] }, "hp": { "Images": [ "hp-img1", "hp-img2" ] } }
about 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

La salida de Array.prototype.map() volverá a ser una matriz. En tu caso, Array.prototype.reduce() es la función ideal para lograrlo:

 const data = [ "apple-img1", "apple-img2", "apple-img3", "apple-img4", "apple-img5", "dell-img1", "dell-img2", "dell-img3", "hp-img1", "hp-img2", ]; const output = data.reduce((prev, curr) => { // get the keyname const [keyName] = curr.split("-"); if (prev[keyName]) { // If the property exists then push to Images array prev[keyName].Images.push(curr); } else { // If the property name does not exist, // create it and add the initial value in the format you want prev[keyName] = { Images: [curr] }; } return prev; }, {}); console.log(output);

about 3 years ago · Juan Pablo Isaza Report

0

Puede utilizar el operador de propagación para realizar esta tarea

 content.map((contentInfo) => { let key = contentInfo.replace(/-img\d$/, "") //Return Company Name without -i{Digit} For Example apple-img1 whould be apple let imgName = contentInfo //Name of the Image data = { Images: {...imgName, key} //Append New Image 2 Array Instead of OverWriting Them } console.log(data); })

Esto debería funcionar.

about 3 years ago · Juan Pablo Isaza Report

0

El operador de propagación se puede usar para agregar valores a una matriz.

 content.map((contentInfo) => { let key = contentInfo.replace(/-img\d$/, ''); //Return Company Name without -i{Digit} For Example apple-img1 whould be apple let imgName = contentInfo; //Name of the Image if (data[key] == undefined) { data[key] = { Images: [imgName], }; } else { data[key] = { Images: [...data[key].Images, imgName], //Append New Image 2 Array Instead of OverWriting Them }; } console.log(data); });

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