-2

I need to loop through array and each array in array that has extra values, push them to their parent array as separate item. I hope this makes sense..

This is the structure of my initial array:

{type:
    [ 0:
        value: "tomato"
    ],
    [ 1:
        {value: "apple",
        [ extras:
           [ 0: { value: "green" } ],
           [ 1: { value: "red" } ]
        ]
    ],
    [ 2:
        value: "pineapple"
    ]
}

What the result would have to look like:

[type:
    [ 0:
        tomato
    ],
    [ 1:
        apple,
        green,
        red
    ],
    [ 2:
        pineapple
    ]
]

What I've tried and failed: (I also commented the error I get on right line)

var response = /* json of first codeblock in question is response from ajax */;

var items = JSON.parse( response );

var type = Object.keys( items )[0];

var myArray = [] 
var count = items[type].lenght;

//Loop through main items in "type"
for( i = 0; i < count; i++ ) {

    var value = items[type][i][value]; 
    myArray[type][i] = [value];  //Uncaught TypeError: Cannot set property '0' of undefined 

    if( items[type][i][extras] ) {

        var extracount = items[type][i][extras].lenght;

        //Loop through extras
        for( k = 0; k < extracount; k++ ) {

            var extra = items[type][i][extras][k][value];
            myArray[type][i].push( extra );
        }
    }     
}

My main problem that I don't understand and that seems to be the problem in my example as well:

If I declare an empty array, how do I:

  • push an item to that array also declaring a new array around that item?
  • push another item to that array that was made around the first item?
Solo
  • 6,687
  • 7
  • 35
  • 67
  • 6
    No, it doesn't makes any sense. You should read more about javascript objects and arrays before doing this. Someone can write the code for you, but you won't learn a thing from it. Your arrays are simply wrong. Anyway, you should explain the expected behavior – Frondor Jan 18 '16 at 18:33
  • @Frondor I disagree - I would learn a lot from this.. and I did my research but I didn't find any good reference for this exact problem. `myArray[type] = [value];` works perfectly but `myArray[type][i] = [value];` doesn't.. Same thing with `push()`. – Solo Jan 18 '16 at 18:35
  • You cannot add indexes into JavaScript arrays. Use objects for those purposes, but as @Frondor said, learn and read more about JavaScript before doing anything. – Zlatan Omerović Jan 18 '16 at 18:35
  • Yes, you are attempting to use and create associative arrays, which are just objects with named properties in javascript. – Kevin Lee Jan 18 '16 at 18:36
  • If you need associative array, you'll have to use Objects, the Javascript array is restricted to only numeric ordered keys and values. – Edson Horacio Junior Jan 18 '16 at 18:38
  • And the code you posted doesn't say anything, because some essential parts are missing, `items` array. – Frondor Jan 18 '16 at 18:39
  • @Solo The most important part is still missing, the CONTENT of `items`. Consider "hardcoding" an sample `response`. And please, always explain what you want to do, or what you intend to do with it – Frondor Jan 18 '16 at 18:42

2 Answers2

1

This is what I believe you want. The following code may be incorrect, because I'm approximating what I believe your items object contains.

var items = {
    type: [
        {
            value: "tomato"
        },
        {
            value: "apple",
            extras: [
                {
                    value: "green"
                }, {
                    value: "red"
                }
            ]
        },
        {
            value: "pineapple"
        }
    ]
};
var myArray = {
    type: []
};


var count = items['type'].length;

//Loop through main items in "type"
for (i = 0; i < count; i++) {

    var subarray = [];
    subarray.push(items['type'][i]['value']);

    if (items['type'][i]['extras']) {
        var extracount = items['type'][i]['extras'].length;
        //Loop through extras
        for (k = 0; k < extracount; k++) {

            var extra = items['type'][i]['extras'][k]['value'];
            subarray.push(extra);
        }
    }
    myArray['type'].push(subarray);
}

Some notes:

You will definitely need to learn the difference between an array and an object in javascript. There are plenty of resources online for this.

When retrieving/manipulating a property prop from an object obj (i.e. for a key-value pair), you will need to use obj.prop or obj['prop']. Note the use of a string in the latter example.

For an array arr, you should use arr.push(value) to push a new value onto the array.

Kevin Lee
  • 1,171
  • 12
  • 30
  • Thanks for answering. I normally know the difference between these two but it gets complicated when object contains several arrays that contains arrays and objects _etc_. Then it gets confusing how does the selection look like and when to use `push()` or something else. – Solo Jan 18 '16 at 19:00
  • A quick way to debug your variables is to create a breakpoint in your code in Developer Tools (or your browser's equivalent) or to use `console.log(items)`. You'll be able to view the contents of the variable, and determine the type (array or object, in this example) of each element. – Kevin Lee Jan 18 '16 at 19:02
0

Your problem is here:

 var value = items[type][i][value]; 

you should change it to

 var value = items[type][i].value; 
dovidweisz
  • 1,215
  • 13
  • 24