Использование рекурсии с .reduce () для удаления определенных свойств из вложенного массива объектов - PullRequest
0 голосов
/ 19 октября 2018

Я работаю с этим массивом вложенных объектов, полученных из API:

const myObj = [
    {
        "$id":"1",
        "Description":"WA State",
        "Place":"WA",
        "Data":[
        {
            "$id":"2",
            "Description":"Years",
            "Indicators":[
            {
                "$id":"3",
                "Year":2017,
                "Points":22191,
                "Goal":"28000",
                "Description":"Year 2017"
            },
            {
                "$id":"4",
                "Year":2018,
                "Points":25994,
                "Goal":"28000",
                "Description":"Year 2018"
            }
            ]
        },
        {
            "$id":"5",
            "Description":"Local Goal",
            "Indicators":[
            {
                "$id":"6",
                "Year":2018,
                "Points":25994,
                "Goal":"28000",
                "Description":"Year 2018"
            }
            ]
        },
        {
            "$id":"7",
            "Description":"Remote Goal",
            "Indicators":[
            {
                "$id":"8",
                "Year":2018,
                "Points":55857,
                "Goal":"84000",
                "Description":"Year 2018"
            }
            ]
        }
        ]
    },

    {
        "$id":"9",
        "Description":"NY State",
        "Place":"NY",
        "Data":[
        {
            "$id":"10",
            "Description":"Years",
            "Indicators":[
            {
                "$id":"11",
                "Year":2017,
                "Points":23451,
                "Goal":"27000",
                "Description":"Year 2017"
            },
            {
                "$id":"12",
                "Year":2018,
                "Points":21953,
                "Goal":"26000",
                "Description":"Year 2018"
            }
            ]
        },
        {
            "$id":"13",
            "Description":"Local Goal",
            "Indicators":[
            {
                "$id":"14",
                "Year":2018,
                "Points":24195,
                "Goal":"25000",
                "Description":"Year 2018"
            }
            ]
        },
        {
            "$id":"15",
            "Description":"Remote Goal",
            "Indicators":[
            {
                "$id":"16",
                "Year":2018,
                "Points":80857,
                "Goal":"90000",
                "Description":"Year 2018"
            }
            ]
        }
        ]
    }
];

Мне нужно удалить все свойства $id и Description из объектов, , ноне мутирует объект .Я пытаюсь сделать это с помощью .reduce():

const props = ['$id', 'Descripcion'];

function removeKeys(obj, prop){
  return props.map( (prop, index) => Object.keys(obj).reduce((object, key) => {
    if (key !== prop[index]) {
      object[key] = obj[key]
    }
    if(object.hasOwnProperty(key))
      removeKeys(obj, prop[index])
    return object
  }, {})
  )
}

console.log( removeKeys(myObj, props) );

// RangeError: Maximum call stack size exceeded

и не работает.Любые идеи о том, как я могу достичь этого, используя .reduce()

PD: Мой вопрос не является дубликатом , потому что яупоминание и определение использования reduce для достижения цели.В другом вопросе ответы об использовании синтаксиса "for...loop".

1 Ответ

0 голосов
/ 19 октября 2018

Вы забыли проверить, является ли свойство объектом или массивом объектов.Также вы использовали prop аргумент removeKeys с prop аргументом вашей функции отображения.В основном этот код поможет:

const props = ['$id', 'Description'];

function removeKeys(obj){
  return Object.keys(obj).reduce((object, key) => {
     if (Array.isArray(obj[key])) {
       object[key] = obj[key].map(item => removeKeys(item));
     }
     
     else if (typeof obj[key] === 'object') {
       console.log(object);
       object[key] = removeKeys(obj[key]);
     }
     
     else if (props.indexOf(key) === -1) {
       object[key] = obj[key];
     }
     
     return object;
  }, {});
}

console.log( removeKeys(myObj) );
<script>
  myObj = 
    {
        "$id":"1",
        "Description":"WA State",
        "Place":"WA",
        "Data":[
        {
            "$id":"2",
            "Description":"Years",
            "Indicators":[
            {
                "$id":"3",
                "Year":2017,
                "Points":22191,
                "Goal":"28000",
                "Description":"Year 2017"
            },
            {
                "$id":"4",
                "Year":2018,
                "Points":25994,
                "Goal":"28000",
                "Description":"Year 2018"
            }
            ]
        },
        {
            "$id":"5",
            "Description":"Local Goal",
            "Indicators":[
            {
                "$id":"6",
                "Year":2018,
                "Points":25994,
                "Goal":"28000",
                "Description":"Year 2018"
            }
            ]
        },
        {
            "$id":"7",
            "Description":"Remote Goal",
            "Indicators":[
            {
                "$id":"8",
                "Year":2018,
                "Points":55857,
                "Goal":"84000",
                "Description":"Year 2018"
            }
            ]
        }
        ]
    };
</script>
...