Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS merge two subarray using map

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading