Skip to content
Advertisement

Nesting for loop automatic

I have a array with objects and those objects consist of some arrays. I wanna loop through the entire array and the array inside the objects. Sound complicated but if you look at the example below it works. However my problem is that right now the length of the variables array is 2, but how can i implement something that makes this type of loop in loop possible if the array is length 4 without hardcoding it since I will get data from a api that varies a lot on the variables.

let wantedArray =[]
let array = [
  { gender: male, value: 10, age: 5,countryofbirth:"Norway" },
  { gender: female, value: 10, age: 2,countryofbirth:"Sweden" },
{ gender: male, value: 15, age: 3,countryofbirth:"Norway" },
{ gender: male, value: 11, age: 4,countryofbirth:"Norway" },
{ gender: female, value: 10, age: 2,countryofbirth:"Finland" },
  ...
]
let variables = [
  { id: gender, options: [male, female] },
  { id: "countryofbirth",  options: ["Norway", "Sweden", "Denmark", "Finland"]}
]
variables[0].options.map((item) => {
  variables[1].options.map((item2) => {
    let currArray = array.filter((currData) =>
      currData[variables[0].id] === item &&
      currData[variables[1].id] === item2);

//lets say that it have come to the point in the loop where item===male and item2==="Norway"

    let currObject ={variables[0].id:item//"Male",
variables[1].id:item2}//"Norway"
let currValues ={}
    currArray.map((data)=>{
    currValues[data.age]=value
})
currObject["values"]=currValues
wantedArray.push(currObject)
/*This means when item===male and item2==="Norway" the function would push {
gender:"Male",
countryofbirth:"Norway,
values:{5:10,3:15,4:11}
} to wantedArray*/
  })
})

Advertisement

Answer

I guess you’re maybe looking for something like

const data = [
  {gender: "male", value: 10, age: 5, countryofbirth: 'Norway'},
  {gender: "female", value: 10, age: 2, countryofbirth: 'Sweden'},
  {gender: "male", value: 15, age: 3, countryofbirth: 'Norway'},
  {gender: "male", value: 11, age: 4, countryofbirth: 'Norway'},
  {gender: "female", value: 10, age: 2, countryofbirth: 'Finland'},
]

// These are all dynamic.
const filter = {gender: "male", countryofbirth: 'Norway'};
const valueKey = 'age';
const valueValue = 'value';

// Find objects with key/values matching all of those in `filter`.
const matching = data.filter((item) => Object.entries(filter).every(([key, value]) => item[key] === value));
console.log(matching);

// Generate a mapping from the found objects using the `valueKey` and `valueValue` variables.
const values = Object.fromEntries(matching.map((item) => [item[valueKey], item[valueValue]]));

// Merge the filter and the values to get the desired result.
console.log({...filter, values});

which finally prints out

{
  gender: 'male',
  countryofbirth: 'Norway',
  values: { '3': 15, '4': 11, '5': 10 }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement