2

i have object with array of names koktelData.strIngredient1 to 15 and values. I want loop that array and create new array with all values from koktelData.strIngredient1 to 15. I tray something like this but new array have 15 elements undefined1 to undefined15.

     var sastojak = koktelData.strIngredient;
  let sastojci = [];
  for (let i = 1; i < 16; i++) {
    var sastojak_niz = koktelData.strIngredient + [i];
    const sastajak = sastojci.push(sastojak_niz);
  }
  console.log(sastojci);
2

2 Answers 2

1

try this out

 let sastojci = [];

 for (let i = 1, j = 0; i < 16; i++, j++) {
        sastojci[j] = koktelData.strIngredient + i
 
 }

 console.log(sastojci);

If coktelData.strIngredient is an array then it should start at 0.

And this is how it should work. If not then contact me and add koktelData.strIngredient to the question so I can test it.

If koktelData.strIngredient is an String then pls show format

Sign up to request clarification or add additional context in comments.

12 Comments

what langues is it and what data type is koktelData.strIngredient?
[link] (ibb.co/0CW3v4N) here is what look exact...i try your example and get same results
pls say language and what datatype is it
it is javasctipt and i try get data from object json...have array with 15 elements strIngredient1 to strIngredient15. i want loop that and get value
try this out but without the json object is difficult, so you should have not only the content but also the variable
|
1

It seems like you want to loop through an object's properties (koktelData.strIngredient1 to koktelData.strIngredient15) and create an array containing their values. You can achieve this using a for loop and dynamic property access. Here's the corrected code:

var sastojci = [];
for (let i = 1; i <= 15; i++) {
  var sastojak_niz = koktelData["strIngredient" + i];
  sastojci.push(sastojak_niz);
}
console.log(sastojci);

In this code:

  1. We initialize an empty array sastojci to store the values.
  2. We use a for loop to iterate from 1 to 15.
  3. Inside the loop, we dynamically access the object properties using bracket notation like koktelData["strIngredient" + i]. This allows us to access koktelData.strIngredient1 through koktelData.strIngredient15.
  4. We push each value into the sastojci array.
  5. Finally, we log the sastojci array to the console, which should contain all the values from koktelData.strIngredient1 to koktelData.strIngredient15.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.