0

I'm having a problem. I have an array as shown below:

0: {type: 'Text', id_a: '123789', value: 'The fifth chapter of the World Première Ducati will be held at the Expo Dubai on December 9th.', number: 2, id: 7}
1: {type: 'Image', id_a: '123789', value: 'b_desertx-dwp2022-2-uc336332-high.jpg', number: 3, id: 8}
2: {type: 'Video youtube', id_a: '123789', value: 'https://youtu.be/SnuyDoXxC4g', number: 5, id: 10}
3: {type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
4: {type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video', number: 2, id: 2}

Of these I want, for example, to take those that have an id_a equal to 123456 and have me return the value (therefore, referring to id_a = 123456 it must return the two relative arrays) then

3: {type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
4: {type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video', number: 2, id: 2}

Except I get this below

{type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
{type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all her secrets with our video', number: 2, id: 2}

without the numbering in order to be able to retrieve the value (therefore using the value attribute) of each of them.

How can I do this?

   var myArr = JSON.parse(this.responseText);
   for(var i = 0, len = myArr.Items.length; i < len; i++){           
        var id_art = myArr.Items[i].id_a;
        if(id_art == 123456) {
            myArr.Items[i];
            console.log(myArr.Items[i]);
   }
a_l_e_x
  • 408
  • 1
  • 6
  • 20
  • So you want to preserve the index in addition to the data? Where do you want to save the index (number of the element)? Also Java and Javascript are different. – Richard K Yu Jan 07 '22 at 23:51
  • Does this answer your question? [Get JavaScript object from array of objects by value of property](https://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects-by-value-of-property) – pilchard Jan 08 '22 at 00:08
  • @RichardKYu Yes exactly. Where to save him doesn't matter; I will need the index later to be able to "extract" the value through the value attribute. I have to use javascript! – a_l_e_x Jan 08 '22 at 10:17
  • JavaScript and Java are two entirely different languages. Please don't tag Java when your question is about JavaScript. – Mark Rotteveel Jan 08 '22 at 10:51
  • I'm very confused. Why do you need the index? The result you showed _already_ contains the value attribute inside of it! – CherryDT Jan 08 '22 at 11:16
  • @CherryDT yes, however, I have to keep making if conditions based on the type attribute and then retrieve the value attribute. If I don't have the indices how can I operate on each of them? Maybe I'm getting confused .. I'm new to programming – a_l_e_x Jan 08 '22 at 11:26
  • I think I have an idea, but can you include what the content of this.responseText is in your question? I just need to make sure of something. Does myArr just consist of Objects of key-value pairs? – Richard K Yu Jan 08 '22 at 14:47
  • @RichardKYu myArr was added to the question – a_l_e_x Jan 08 '22 at 14:58
  • Let me know if this answer helps. I am thinking that what you have might be a slightly different data structure from what I think it is, but you can still get the same results by adding in the new parts in my code (besides the initialization of myArr) to your old code, assuming we need to use .Items to access each entry in myArr. – Richard K Yu Jan 08 '22 at 15:23
  • @RichardKYu I get the output I wrote under my question – a_l_e_x Jan 08 '22 at 15:36

1 Answers1

1

So based on the edit the array with actual information we want is the value of the Items key.

myArr doesn't seem to be an array, but it's actually a key-value pair based on the edit as well.

Here is my attempt:

var myArr = JSON.parse(this.responseText);

//console.log(myArr.Items)
//Declare and initialize k-v pair.
var results = {};
for (var i = 0, len = myArr.Items.length; i < len; i++) {
    var id_art = myArr.Items[i].id_a;
    if (id_art == 123456) {
        //console.log(i, myArr.Items[i]);
        //Create the key-value pair and store the index information in the key.
        results[i] = myArr.Items[i];
    }
}

console.log(results);

Output:

{
  '3': {
    type: 'Image',
    id_a: '123456',
    value: 'moto_guzzi_v100_mandello.jpg',
    number: 3,
    id: 3
  },
  '4': {
    type: 'Text',
    id_a: '123456',
    value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video',
    number: 2,
    id: 2
  }
}

Explanation: Since you have specified you do not care how the data is stored. I have put it in the key of a new key-value Object in Javascript (do they call these dictionaries or hashmaps here?).

Thus, you can access them now by cycling through the elements in the dictionary, or getting a list of just keys in the dictionary and choosing which value you would like to access.

For instance, to print out a list of keys that exist in this object, you might use:

for (let value of Object.keys(results)) {
    console.log(value)
}

Let me know if I have understood you correctly.

Edit

To get the output mentioned in your comment, now using while:

var x = 0;
while (x < Object.entries(results).length) {
    //console.log(Object.entries(results)[x][1]);
    if (Object.entries(results)[x][1].type == "Image"){
        console.log("The index is: ", Object.entries(results)[x][0]);
        console.log("The value is: ", Object.entries(results)[x][1].value);
    }
    x++;

}

Output: enter image description here

Richard K Yu
  • 2,152
  • 3
  • 8
  • 21
  • I remind you that I wrote the output of your example in my question. Also about the change if I put var myArr = JSON.parse (this.responseText) .Items; I no longer get the length value. In fact it gives me the following error: Cannot read properties of undefined (reading 'length') – a_l_e_x Jan 08 '22 at 15:41
  • I've changed the code to work with what you've already got to work with Items. It should be clearer that way. You can copy and paste it directly and see if it works this time. If you're interested in the error, it's because we're basically calling Object.Items.Items.length if you don't remove the ".Items" in the loop too after putting it in the initialization of myArr. – Richard K Yu Jan 08 '22 at 15:47
  • Everything ok, thank you so much. If I wanted to loop (say while) on the elements of this array why can't I use length? I've tried using results.length but it's undefined. – a_l_e_x Jan 08 '22 at 19:22
  • Glad I can help you! Try: console.log(Object.keys(results).length) . Here, I am just using the number of keys in the dictionary to stand for the length, which should be ok in this limited case. For more information about access, please see the article here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries – Richard K Yu Jan 08 '22 at 19:29
  • Perfect, thank you so much again. Last question; I have seen the documentation on Object.keys you provided me with; this is my first time using this and i am also new to programming. Now doing a loop on all the elements, I would like for example to see if **type** is an *image* and return its **value**, so for example *moto_guzzi_v100_mandello.jpg*. I tried as written in the "WHILE" section above the main question but I get the error "Cannot convert undefined or null to object". What did I do wrong? – a_l_e_x Jan 08 '22 at 23:36
  • @s_o_p_h_i_a If your original question is answered adequately, it will be easier accept this one and ask a new question (I can see more details in a new question too). Comments should generally not be used for extended question and answer according to the site guidelines. – Richard K Yu Jan 08 '22 at 23:41
  • ok i will learn for next time. Only now I'm unable to ask new questions. This one I have done is the last one regarding my problem. Received the answer I will not ask more questions about this. – a_l_e_x Jan 08 '22 at 23:51
  • @s_o_p_h_i_a If you don't need to make it a while loop, I have included an edit for you that might help. – Richard K Yu Jan 08 '22 at 23:54
  • perfect, thank you so much – a_l_e_x Jan 09 '22 at 12:22