how to merge data from different array to a combined array in json form.
let NAME: any[] =[]
let TYPE: any[] = []
let OBJ: any[] =[]
for (var i=0;i<getdata.length;i )
{
var p =getdata[i].name;
**var a =NAME.push(p);** // pushing data to Name
for (var j in getTypes[i])
{
if (getdata[i].name ==getTypes[i][j].data.name) // get type is having req. data here
{
var k = getTypes[i][j].name ;
**var s =TYPE.push(k);** //pushing data to type
}
}
for (var j in getobj[i])
{
if (getdata[i].name ==getobj[i][j].library.name)
{
var o = getobj[i][j].name ;
**var g = OBJ.push(o);** // pushing data to OBJ
}
}
}
console.log(NAME); // result getting :- ['A','B','C']
console.log(TYPE); // result getting :- ['A1','A2','B1','B2','C1','C2']
console.log(OBJ); // result getting :- ['AA1','AA2','BB1','BB2','CC1','CC2']
});
Data required like this :
{ id=1; NAME: A OBJ:'A1','A2' TYPE:'AA1','AA2' }
{ id=2; NAME: B OBJ:'B1','B2' TYPE:'BB1','BB2' }
{ id=C; NAME: C OBJ:'C1','C2' TYPE:'CC1','CC2' }
CodePudding user response:
Assuming that getdata, getTypes and getobj match the following criteria:
getdatais an array of objects & each object hasnameas a propgetobjis a 2-dimensional array such thatgetobj[i]matches with the data ongetdata[i]and that each element in the inner-array constitutes of:library.nameandnamegetTypesis a 2-dimensional array such thatgetType[i]matches with the data ongetdata[i]and that each element in the inner-array constitutes of:data.nameandname.
the below solution is one potential way to achieve the desired results:
const desiredObjectArray = getdata.map((data, idx) => ({
id: idx,
NAME: data.name,
OBJ: getobj[idx].filter(
obj => obj.library.name === data.name
).map(objData => objData.name),
TYPE: getTypes[idx].filter(
typ => typ.data.name === data.name
).map(typData => typData.name)
}));
Explanation / Approach
- Use
.mapto iterate ongetdataarray. - Populate the
idandNAMEdirectly - For
OBJiterate over the array atgetobj[idx], filter in only those elements wherelibrary.namematches thegetdata[idx].name, and then map the object to obtain just thename - For
TYPEiterate over the array atgetTypes[idx], filter only those wheredata.namematchesgetdata[idx].name, and then map the object to return just thename
CodePudding user response:
const NAME = ['A','B','C']
const OBJ = ['A1','A2','B1','B2','C1','C2']
const TYPE = ['AA1','AA2','BB1','BB2','CC1','CC2']
const result = []
NAME.forEach((item, index) => {
const obj = []
const type = []
obj.push(obj[index], obj[index 1])
type.push(type[index], type[index 1])
result.push({
id: index 1,
NAME: item,
OBJ: obj,
TYPE: type
})
})
return result
