小编典典

在与ES6深度嵌套的对象的javascript数组中寻找价值

algorithm

在对象数组中,我需要找到value-- keyactivity:但是,activity key可以将其深深地嵌套在数组中,如下所示:

const activityItems = [
    {
        name: 'Sunday',
        items: [
            {
                name: 'Gym',
                activity: 'weights',
            },
        ],
    },
    {
        name: 'Monday',
        items: [
            {
                name: 'Track',
                activity: 'race',
            },
            {
                name: 'Work',
                activity: 'meeting',
            },
            {
                name: 'Swim',
                items: [
                    {
                        name: 'Beach',
                        activity: 'scuba diving',
                    },
                    {
                        name: 'Pool',
                        activity: 'back stroke',
                    },
                ],
            },
        ],    
    },
    {} ...
    {} ...
];

因此,我编写了一个递归算法来确定数组中是否存在某个活动:

let match = false;
const findMatchRecursion = (activity, activityItems) => {
    for (let i = 0; i < activityItems.length; i += 1) {
        if (activityItems[i].activity === activity) {
            match = true;
            break;
        }

        if (activityItems[i].items) {
            findMatchRecursion(activity, activityItems[i].items);
        }
    }

    return match;
};

有没有ES6办法确定活动是否存在于像这样的数组中?

我尝试过这样的事情:

const findMatch(activity, activityItems) {
    let obj = activityItems.find(o => o.items.activity === activity);
    return obj;
}

但这不适用于深层嵌套的活动。

谢谢


阅读 515

收藏
2020-07-28

共1个答案

小编典典

您可以使用some()方法和递归来查找活动是否存在于任何级别并返回true / false作为结果。

const activityItems = [{"name":"Sunday","items":[{"name":"Gym","activity":"weights"}]},{"name":"Monday","items":[{"name":"Track","activity":"race"},{"name":"Work","activity":"meeting"},{"name":"Swim","items":[{"name":"Beach","activity":"scuba diving"},{"name":"Pool","activity":"back stroke"}]}]}]



let findDeep = function(data, activity) {

  return data.some(function(e) {

    if(e.activity == activity) return true;

    else if(e.items) return findDeep(e.items, activity)

  })

}



console.log(findDeep(activityItems, 'scuba diving'))
2020-07-28