Search key and return value in nested object

前端 未结 4 798
盖世英雄少女心
盖世英雄少女心 2021-01-28 17:02

Lets say my object looks like the below. Its a mix of different arrays and parents, no hierarchical order. e.g.

\"person\": {
\"id\": 12345,
\"name\": \"John Doe         


        
4条回答
  •  佛祖请我去吃肉
    2021-01-28 17:40

     returnValuesForAttribute = (attr) => {
        let mobile = {};
        let index = 0;
        Object.values(person).map(first_level => {
            if (Array.isArray(first_level)) {
                first_level.map(el => {
                    if (Object.keys(el).includes(attr)) {
                        mobile[index] = el[attr];
                        index++;
                    }
                    Object.values(el).map(second_level => {
                        if (typeof second_level === 'object' && second_level[attr]) {
                            mobile[index] = second_level[attr];
                            index++;
                        }
                    })
                })
            }
        });
        return mobile;
    }
    returnValuesForAttribute('mobile');
    

    Output: {0: "877-123-1234", 1: "877-123-1234", 2: "877-123-1234", 3: "877-123-1234"}

提交回复
热议问题