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
Creando dinámicamente un objeto con una matriz dentro

Estoy tratando de crear dinámicamente un objeto JS que tiene una matriz dentro como esta:

 //other values omitted for clarity "items": [ { "name": "T-Shirt", "unit_amount": { "currency_code": "USD", "value": "90.00" }, "quantity": "1", "category": "PHYSICAL_GOODS" }, { "name": "Shoes", "unit_amount": { "currency_code": "USD", "value": "45.00" }, "quantity": "2", "category": "PHYSICAL_GOODS" } ],

Puedo crear un valor único con este código:

 var product = {}; product.name = "T-Shirt"; product.quantity = "1"; product.category = "PHYSICAL_GOODS"; var subproduct = {}; subproduct.currency_code = "USD"; subproduct.value = "90.00"; product.unit_amount = subproduct; var jsonString= JSON.stringify(product);

que crea:

 { "name": "T-Shirt", "unit_amount": { "currency_code": "USD", "value": "90.00" }, "quantity": "1", "category": "PHYSICAL_GOODS" }

¿Cómo puedo sumar los valores creados dentro de la matriz? Tengo un evento onclick para proporcionar los valores de cualquier "elemento" dado en el ejemplo. Para mayor claridad, no sé de antemano cuántos "elementos" tendrá la matriz.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Está en el camino correcto, simplemente itere su código y colóquelo en una matriz:

 var productList = []; for (var i = 0 ; i < 2; i++) { // your code var product = {}; product.name = "T-Shirt"; product.quantity = "1"; product.category = "PHYSICAL_GOODS"; var subproduct = {}; subproduct.currency_code = "USD"; subproduct.value = "90.00"; product.unit_amount = subproduct; productList.push(product); } var answer = JSON.stringify(productList); console.log(answer);

about 4 years ago · Juan Pablo Isaza Report

0

Para agregar el objeto a una matriz, debe usar el método de matriz .push() .

Podrías hacerlo de la siguiente manera:

 // Object which has a property `items`, where we will store product objects var main = { items: [] }; // Create the full product object var product = { name: "T-Shirt"; quantity: "1"; category: "PHYSICAL_GOODS"; unit_amount: { currency_code = "USD"; value = "90.00"; } }; // Push the new object to the `items` array main.items.push(product);
about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!