How can I make an array instaed of nested arrays in Javascript from myArray?

I need to split riskTypeNo from each object and then assign selectedValue to each value and then create an array with all the objects. With my code I am getting nested arrays

    const myArray = [
  {
    "fieldID": 1681977,
    "riskTypeNo": "A1;M1",
    "selectedValue": "4"
  },
  {
    "fieldID": 1681984,
    "riskTypeNo": "C6;M1",
    "selectedValue": "1"
  },
  {
    "fieldID": 1682084,
    "riskTypeNo": "A13;C6;M1;D5",
    "selectedValue": "3"
  }
];


console.log(
    myArray.map(item1 => {
    const riskTypeNo =  item1.riskTypeNo.split(";").map(item2 => ({ "riskTypeNo": item2,  "selectedValue": item1.selectedValue }));
    return riskTypeNo;   
  })
);
Desired Result is:
[ 
{ riskTypeNo: "A1", selectedValue: "4" }, { riskTypeNo: "M1", selectedValue: "4" }], [{ riskTypeNo: "C6", selectedValue: "1" }, { riskTypeNo: "M1", selectedValue: "1" }], [{ riskTypeNo: "A13", selectedValue: "3" }, { riskTypeNo: "C6", selectedValue: "3" }, { riskTypeNo: "M1", selectedValue: "3" }, { riskTypeNo: "D5", selectedValue: "3" } 
}]

I am not the super js specialist but I guess this could not be done with a map function.

I would create my own function with loops like that:

let resultArray = [];
myArray.forEach( (entry) =>
{
    let risks = entry.riskTypeNo.split(“;”);
    risks.forEach( (risk) =>
    {
         let result = {};
         result.riskTypeNo = risk;
         result.selectedValue = entry.selectedValue;
         resultArray.push(result);
    });
});
2 Likes

What you are saying is you want this. Three arrays

[ 
  { riskTypeNo: "A1", selectedValue: "4" }, 
  { riskTypeNo: "M1", selectedValue: "4" }
],
[
  { riskTypeNo: "C6", selectedValue: "1" }, 
  { riskTypeNo: "M1", selectedValue: "1" }
], 
[
  { riskTypeNo: "A13", selectedValue: "3" }, 
  { riskTypeNo: "C6", selectedValue: "3" }, 
  { riskTypeNo: "M1", selectedValue: "3" }, 
  { riskTypeNo: "D5", selectedValue: "3" } 
]

Well they need to be contained/assigned somehow. A bit confused by your requirement.

Edit to do as Thallius has done, you can use flatMap

const fields = [
  {
    "fieldID": 1681977,
    "riskTypeNo": "A1;M1",
    "selectedValue": "4"
  },
  {
    "fieldID": 1681984,
    "riskTypeNo": "C6;M1",
    "selectedValue": "1"
  },
  {
    "fieldID": 1682084,
    "riskTypeNo": "A13;C6;M1;D5",
    "selectedValue": "3"
  }
]
const getRiskTypes = function (fields) {
  return fields.flatMap(({riskTypeNo, selectedValue}) => {
    const riskTypes = riskTypeNo.split(';')
    
    return riskTypes.map((riskTypeNo) => {
       return { riskTypeNo, selectedValue }
    })
  })
}
  
console.log(JSON.stringify(getRiskTypes(fields), null, 2))
2 Likes

Thanks that is what I want.

Cool, that is new to me too. Thanks

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.