I have an array, grpList
contains unique id's & unique names.
grpList = [
{ name: "grp1", id: "1" },
{ name: "grp2", id: "2" },
{ name: "grp3", id: "3" },
{ name: "grp4", id: "4" },
{ name: "grp5", id: "5" },
{ name: "grp6", id: "6" }
]
Another type of Array, In the below array currentList, it has only 2 types i.e G
or Q
, with type 'G'
it has array values with unique names. These names are mapped from the grpList
Array.
currentList = [
{ name: "name1", type: "G", values: ["grp1", "grp3"] },
{ name: "name2", type: "Q", values:"abcd" },
{ name: "name3", type: "G", values: ["grp1", "grp5"] },
{ name: "name4", type: "Q", values:"frd" },
{ name: "name5", type: "G", values: ["grp1", "grp2"] },
{ name: "name6", type: "Q", values:"erer" }
]
Now What I want is that create a new array that consist data of type currentList
i.e it should contains properties of currentList
array and it should mapped with ids corresponding to grpList
array.
Example:
newArry = [
{ name: "name1", type: "G", values: ["1", "3"] },
{ name: "name2", type: "Q", values:"abcd" },
{ name: "name3", type: "G", values: ["1", "5"] },
{ name: "name4", type: "Q", values:"frd" },
{ name: "name5", type: "G", values: ["1", "2"] },
{ name: "name6", type: "Q", values:"erer" }
]
CodePudding user response:
You can do it like this:
const grpList = [
{ name: "grp1", id: "1" },
{ name: "grp2", id: "2" },
{ name: "grp3", id: "3" },
{ name: "grp4", id: "4" },
{ name: "grp5", id: "5" },
{ name: "grp6", id: "6" }
];
const currentList = [
{ name: "name1", type: "G", values: ["grp1", "grp3"] },
{ name: "name2", type: "Q", values:"abcd" },
{ name: "name3", type: "G", values: ["grp1", "grp5"] },
{ name: "name4", type: "Q", values:"frd" },
{ name: "name5", type: "G", values: ["grp1", "grp2"] },
{ name: "name6", type: "Q", values:"erer" }
]
const newList = currentList.map(item => {
if (item.type == 'Q') return item;
const values = item.values.map(value => {
const grpItem = grpList.find(grp => grp.name == value);
return grpItem.id;
})
return {...item, values}
});
console.log(newList)
CodePudding user response:
You can iterate over each value in each element and remove grp
with a replace
:
const currentList = [
{ name: "name1", type: "G", values: ["grp1", "grp3"] },
{ name: "name2", type: "Q", values:"abcd" },
{ name: "name3", type: "G", values: ["grp1", "grp5"] },
{ name: "name4", type: "Q", values:"frd" },
{ name: "name5", type: "G", values: ["grp1", "grp2"] },
{ name: "name6", type: "Q", values:"erer" }
];
const result = currentList.map(el => {
if (!Array.isArray(el.values) || el.type !== 'G') return el;
return {...el, values: el.values.map(v => v.replace('grp', ''))};
});
console.log(result);