I use the following to merge two arrays:
var mySeries = [
{ name: '4', data: [4] },
{ name: '3', data: [3] }
];
var mySeries1 = [
{ name: '5', data: [0] },
{name: '4', data:[0]},
{name: '3', data:[0]},
{name: '2', data:[0]},
{ name: '1', data: [0] }
];
var res = mySeries1.map(obj => mySeries.find(o => o.name === obj.name) || obj);
console.log(res);
Works great; however, my challenge is my array is structured as:
var myArray = [{
mySeries : [
{ name: '4', data: [4] },
{ name: '3', data: [3] }],
mySeries1 : [
{ name: '5', data: [0] },
{ name: '4', data: [0] },
{ name: '3', data: [0] },
{ name: '2', data: [0] },
{ name: '1', data: [0] }]
}];
];
So I need to map subarrays, tried using the following:
var res = myArray.mySeries1.map(obj => myArray.mySeries.find(o => o.name === obj.name) || obj);
I get this error:
Cannot read properties of undefined (reading 'map')
How can I point to the subarray?
CodePudding user response:
var myArray = [{
mySeries : [
{ name: '4', data: [4] },
{ name: '3', data: [3] }],
mySeries1 : [
{ name: '5', data: [0] },
{ name: '4', data: [0] },
{ name: '3', data: [0] },
{ name: '2', data: [0] },
{ name: '1', data: [0] }
]
}];
var res = myArray[0].mySeries1.map(obj => myArray[0].mySeries.find(o => o.name === obj.name) || obj);
console.log(res)
CodePudding user response:
you could change your array to dictionary and iterate it like you already did.
var myArray = {
mySeries : [
{ name: '4', data: [4] },
{ name: '3', data: [3] }],
mySeries1 : [
{ name: '5', data: [0] },
{ name: '4', data: [0] },
{ name: '3', data: [0] },
{ name: '2', data: [0] },
{ name: '1', data: [0] }]
};
i.e. var res = myArray.mySeries1.map(obj => myArray.mySeries.find(o => o.name === obj.name) || obj);