How to filter this object, for example, by age?

const teams = { '0': { Name: 'Vasa', Age: 25 }, '1': { Name: 'Alex', Age: 20 } } console.log(teams); 

Found a similar topic, as for example this one , but too difficult.

Thank you in advance.

    2 answers 2

    You can do so. Not the most universal example, but still

     let result = {} let teams = { '0': { Name: 'Vasa', Age: 25 }, '1': { Name: 'Alex', Age: 20 } } for (i in teams) { let team = teams[i] // Ниже условие фильтрации if (team.Age === 20) { result[i] = team } } console.log(result) 

    It would be better if the teams variable is an array, then you can write more flexible and concise code, for example:

      let teams = [{ Name: 'Vasa', Age: 25 },{ Name: 'Alex', Age: 20 }] let result = teams.filter(team => team.Age === 20) console.log(result) 

    • Thank you very much. From: - Anatoliy.CHA
    • This way you fill the result links to the teams fields. So, when you change teams , the result will also change (which can lead to an error). This should be indicated in the answer. - yar85

     const teams = { '0': { Name: 'Vasa', Age: 25 }, '1': { Name: 'Alex', Age: 20 } }; let filtered = filterBySubField(teams, 'Age', 20); console.log(JSON.stringify(filtered, null, 2)); // возвращает копию объекта obj, содержащую только те поля-объекты, у которых поле subField === value function filterBySubField(obj, subField, value) { let result = {}; for (let k in Object.keys(obj)) { if (obj[k][subField] === value) result[k] = Object.assign({}, obj[k]); } return result; }