JS使用map合并两个子数组

JS merge two subarray using map

我使用以下方法合并两个数组:

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);

效果很好;然而,我的挑战是我的数组结构如下:

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.mySeries1.map(obj => myArray.mySeries.find(o => o.name === obj.name) || obj);

我收到这个错误:

Cannot read properties of undefined (reading 'map')

如何指向子数组?

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)

您可以将数组更改为字典并像您已经做的那样对其进行迭代。

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.mySeries1.map(obj => myArray.mySeries.find(o => o.name === obj.name) || obj);