-1

Little update (Just for clarify the "duplicate question flag")

This question is slightly different from this one, because in there we are talking about some ways to loop an array using javascript. In my case we are talking about 'how to modify' an existing associative array of arrays using javascript. That's not exactly the same concept, cause for my specific case we could try to apply also something different from a loop.

I have this data structure obj reproduced with a console.log in chrome browser:

var obj = {
    key_1: [{
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }, {
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }],
    key_2: [{
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }, {
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }]
};

Loop and push inside a new array

I'm trying to get as output result from obj a new array called new_arr filled with only the prop_2 and prop_3 and the key value. Like in the example result below:

new_arr = [ 
   ["some_value_2","some_value_3","key_1"],
   ["some_value_2","some_value_3","key_1"],
   ["some_value_2","some_value_3","key_2"],
   ["some_value_2","some_value_3","key_2"]
          ];

So I have tried to perform a for loop and inside it I have push only the required properties, like the example code below:

    new_arr = [];

    for (var key in obj) {
       new_arr.push(
       obj[key][0].prop_2 + ', ' +  
       obj[key][0].prop_3 + ', ' + 
       key);
    }
    console.log(new_arr);

Output problem

The problem that stuck me is related to the fact that the new_arr contains just the [0] index array. So the array at index 1 is not pushed inside. Is there a way to access to all the index properties and perform the loop for all the index (not only for the case index[0])?

Any suggestions? Thanks in advice!

UgoL
  • 839
  • 2
  • 13
  • 37
  • 1
    Sure, like in any programming language you can use a for loop: `for (var i=0;i – slebetman Nov 06 '17 at 17:00
  • Possible duplicate of [Loop through an array in JavaScript](https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript) – shawon191 Nov 06 '17 at 17:01
  • You can use extend and make your new array extend default that has all properties. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends – Marco Nov 06 '17 at 17:01
  • You shouldn't be concatenating strings with commas, you should be creating arrays that you push. – Barmar Nov 06 '17 at 17:12
  • Your rejection of the duplicate is wrong. You're not modifying anything in the original array, you're just asking how to loop through the nested arrays to get all the elements instead of just the `[0]` element. What you do with them is irrelevant. – Barmar Nov 06 '17 at 17:19

2 Answers2

2

Use nested loops.

var arr = {
    key_1: [{
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }, {
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }],
    key_2: [{
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }, {
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }]
};

var newarr = [];

for (var key in arr) {
    arr[key].forEach(obj => newarr.push([obj.prop_2, obj.prop_3, key]));
}

console.log(newarr);

Note that the value you push should be an array, according to your desired output. A string with values concatenated with commas is not the same thing.

arr[key].forEach(function)

loops over the array in arr[key], calling the function on each element, which are the nested objects in your data. The function above creates an array containing the prop_2 property, prop_3 property, and key, and pushes that onto the new_arr array.

Fot the modified scenario, just add another level of nested for loop:

for (var key1 in obj) {
    for (var key2 in obj[key1]) {
        obj[[key1][key2].forEach(o => newarr.push([o.prop_2, o.prop_3, key1, key2]));
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you @Barmar, this is exactly what I'm searching for. The output result is perfect. Can you please explain me in a few words how this forEach with obj works? Cause we are assuming that arr is like an array of objects? – UgoL Nov 06 '17 at 17:26
  • I've added some explanation. But didn't you see the `forEach` examples in the possible duplicate? – Barmar Nov 06 '17 at 17:30
  • `arr` is not an array of objects, it's an object. Each of its properties is an array of objects. – Barmar Nov 06 '17 at 17:32
  • Thank you for the additional info and for the snippet. I think I have got the point. – UgoL Nov 06 '17 at 17:34
  • I want to ask you just a slightly different scenario.. consider to have also other 'keys' that contains all the existing 'key_1', 'key_2', 'key_3' in `arr`. For example 'key_0' that contains everything. How would be the loop considering that we need to iterate over 2 nested keys? – UgoL Nov 06 '17 at 21:53
  • Just use `arr.key_0` instead of `arr` everywhere. – Barmar Nov 06 '17 at 21:56
  • But If I have for example more than one key? For example 'key_0' to ten different keys. How can I handle multiple keys? – UgoL Nov 06 '17 at 21:58
  • I guess I didn't understand your modification. Sounds like you need to post a new question. – Barmar Nov 06 '17 at 22:06
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158356/discussion-between-ugol-and-barmar). – UgoL Nov 06 '17 at 22:12
  • Native array.forEach() has reached a coverage of ~98% ? Wow, didn't realize that before. – Matschek Nov 07 '17 at 08:59
1

Make an inner loop for the index

for (var key in arr) {
for (var innerKey in arr[key]) {
   new_arr.push( [
   arr[key][innerKey].prop_2,  
   arr[key][innerKey].prop_3, 
   key ])
}
}
Matschek
  • 205
  • 1
  • 9
  • 1
    [Why is using “for…in” with array iteration a bad idea?](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – Andreas Nov 06 '17 at 17:06
  • As long as I don't know anything about the inner array keys (if index is continous or not), `for..in` is the better way than `for i` – Matschek Nov 06 '17 at 17:12
  • The problem with your solution is that the output result values are probably concatenated, so for each array index value we have something like: ["some_value_2, some_value_3 , key_1"] with just one double quote. The optimal solution would be to have something like: ["some_value_2","some_value_3","key_1"] – UgoL Nov 06 '17 at 17:21
  • @UgoL, you're right, I just cared for the index problem as I edited your code... Fixed it. – Matschek Nov 06 '17 at 17:32
  • 1
    It's not a matter of _"do I know xyz"_. Is it an array? -> `for (...; ...; ...)`; Is it an object? -> `for (... in ...)` – Andreas Nov 07 '17 at 06:52
  • @Andreas I don't agree with this rule of thumb here. If the array index is for example 0, 1 and 4: a `for i` is a inconvenient way to iterate it. index 2 and 3 have null values in this case and need further differentiation in the code. A `for in` iterates over 0, 1 and 4. Yes, it treats the array as an object, but this is fine here in my opinion. – Matschek Nov 07 '17 at 08:52