[英]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.我需要从每个对象中拆分 riskTypeNo ,然后将 selectedValue 分配给每个值,然后创建一个包含所有对象的数组。 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" }
}]
You can return the split array from inside the map
method.您可以从
map
方法内部返回拆分数组。 But that will get you an array of arrays.但这会给你一个数组数组。 To flatten those arrays just use the array method
flat
.要展平这些数组,只需使用数组方法
flat
。
This should work:这应该有效:
const result = myArray.map(el => {
const riskTypes = el.riskTypeNo.split(";").map(riskTypeNo => ({
riskTypeNo,
selectedValue: el.selectedValue,
}))
return riskTypes;
}).flat();
Here's one way:这是一种方法:
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" } ]; const result = myArray.reduce((prev,cur) => { let obj = []; cur.riskTypeNo.split(';').forEach((n) => { obj.push({riskTypeNo: n, selectedValue: cur.selectedValue}); }); prev.push(...obj); return prev; }, []); console.log(result);
you can use this method instead :您可以改用此方法:
const newArray = [];
myArray.forEach((item1) => {
item1.riskTypeNo.split(";").forEach((item2) => {
newArray.push({ riskTypeNo: item2, selectedValue: item1.selectedValue });
});
});
result will be in newArray
.结果将在
newArray
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.