Creating multiple object loops over an array

So, I have an array that stores hobbies for each user in an array inside the object.

var hobbies = [
  {
    "id": 1,
    "hobbies": []
  },

  {
    "id": 2,
    "hobbies": [
      "football"
    ]
  },
  {
    "id": 3,
    "hobbies": [
      "football",
      "basketball"
    ]
  }
]

What I want to return is a new array of objects, but each hobby is divided into its own object, as shown below.

var result = [
  {
    "id": 2,
    "hobby": "football"
  },
 {
    "id": 3,
    "hobby": "football"
  },
 {
    "id": 3,
    "hobby": "basketball"
  }
]

What still exists

hobbies.filter((f, i) => f.hobbies.length > 0).map((p, i) => {
    while (i < p.hobbies.length) {
 return { id : p.id, hobby : p.hobbies[i] };
}
  });

which returns only

[
  {
    "id": 2,
    "hobby": "football"
  },
  {
    "id": 3,
    "hobby": "basketball"
  }
]
+4
source share
4 answers

You can use array#reducewith array#map. Iterate through each object, and then repeat each hobby hobbiesand create an object.

var hobbies = [ { "id": 1, "hobbies": [] }, { "id": 2, "hobbies": [ "football" ] }, { "id": 3, "hobbies": [ "football", "basketball" ] } ],
    result = hobbies.reduce((r, {id, hobbies}) => r.concat(hobbies.map(hobby => ({id, hobby}))), []);
console.log(result);
Run code
+1
source

You need to use the inner loop to scroll through the hobby and push them one by one on the target array:

var hobbies = [{
    "id": 1,
    "hobbies": []
  },

  {
    "id": 2,
    "hobbies": [
      "football"
    ]
  },
  {
    "id": 3,
    "hobbies": [
      "football",
      "basketball"
    ]
  }
];

var result = hobbies.reduce((acc, item) => {
  item.hobbies.forEach(hobby => {
    acc.push({
      id: item.id,
      hobby: hobby
    });
  });
  return acc;
}, []);

console.log(result);
Run code
0
source

array.prototype.reduce:

var hobbies = [{"id": 1,"hobbies": []},{"id": 2,"hobbies": ["football"]},{"id": 3, "hobbies": ["football","basketball"]}];

var res = hobbies.reduce((m, o) => (o.hobbies.forEach(h => m.push({id: o.id, hobby: h})), m), []);

console.log(res);
0

, :

hobbies.

Then for each element in the array (which represents the person) you want to iterate over your hobbies, and for each of these hobbies you need to click the object, which consists of the profile identifier and the hobby, into the resultsarray that I created earlier.

var hobbies = [{ "id": 1, "hobbies": [] }, { "id": 2, "hobbies": [ "football" ] }, { "id": 3, "hobbies": [ "football", "basketball" ] } ];

let result = [];

hobbies.forEach(function(profile){
  profile.hobbies.forEach(function(hobby){
    result.push(
            {
        "id": profile.id,
        "hobby": hobby
      }
    );
  });
});

console.log(result)
Run code

Update: Other answers using Array.reduce (a more specialized loop) will further reduce the above code.

0
source

Source: https://habr.com/ru/post/1694290/


All Articles