What I want to do is merging 3 strings according to the sequence in both the lists.
For example, in an array I have these 3 items which have their data in string form:
1: {
permissionIDList: "1,2,3"
permissionNameList: "Admin Role,Admin Role,Bulletin Board"
permissionTypeList: "view,edit,view"
}
I want to merge the lists and map it into both value and label so that it will become:
0: {value: 1, label: Admin Role - view}
1: {value: 2, label: Admin Role - edit}
2: {value: 3, label: Bulletin Board - view}
CodePudding user response:
Array.reduce
implementation
const data = {
permissionIDList: "1,2,3",
permissionNameList: "Admin Role,Admin Role,Bulletin Board",
permissionTypeList: "view,edit,view",
};
const [permissionIDList, permissionNameList, permissionTypeList] = [data.permissionIDList.split(','), data.permissionNameList.split(','), data.permissionTypeList.split(',')];
const merger = permissionIDList.reduce((acc, curr, index) => {
acc[curr] = {
value: curr,
label: `${permissionNameList[index]} - ${permissionTypeList[index]}`
}
return acc;
}, {});
console.log(merger);
If your final data response is an array, you can make use of Array.map
const data = {
permissionIDList: "1,2,3",
permissionNameList: "Admin Role,Admin Role,Bulletin Board",
permissionTypeList: "view,edit,view",
};
const [permissionIDList, permissionNameList, permissionTypeList] = [data.permissionIDList.split(','), data.permissionNameList.split(','), data.permissionTypeList.split(',')]
const merger = permissionIDList.map((node, index) => ({
value: node,
label: `${permissionNameList[index]} - ${permissionTypeList[index]}`
}));
console.log(merger);
CodePudding user response:
This code gives what you need:
const strings = {
permissionIDList: "1,2,3",
permissionNameList: "Admin Role,Admin Role,Bulletin Board",
permissionTypeList: "view,edit,view"
}
const permissionIDList = strings.permissionIDList.split(',');
const permissionNameList = strings.permissionNameList.split(',');
const permissionTypeList = strings.permissionTypeList.split(',');
const result = [];
for(let i = 0; i < permissionIDList.length; i ){
result.push({
value: permissionIDList[i],
label: permissionNameList[i] " - " permissionTypeList[i]
});
}
console.log(result);
CodePudding user response:
Another implementation could be:
const value = {
permissionIDList: "1,2,3",
permissionNameList: "Admin Role,Admin Role,Bulletin Board",
permissionTypeList: "view,edit,view",
}
Object.entries(value).map((item,i) => {
const permissionNameList = value['permissionNameList'].split(','[i];
const permissionTypeList = value['permissionTypeList'].split(','[i];
const permissionIDList = value['permissionIDList'].split(',')[i];
return {
value: permissionIDList,
label: `${permissionNameList} - ${permissionTypeList}`
}
})