Suppose we have an array filled with objects :
people = [
{id: "1", name: "abc", gender: "m", age:"15", country:"USA" },
{id: "2", name: "def", gender: "m", age:"25", country:"BRA" },
{id: "3", name: "ghi", gender: "f", age:"05", country:"CHI" },
{id: "4", name: "jkl", gender: "m", age:"35", country:"RUS" },
{id: "5", name: "mno", gender: "m", age:"41", country:"JAP" },
{id: "6", name: "pqr", gender: "f", age:"30", country:"COL" },
{id: "7", name: "stu", gender: "f", age:"31", country:"CAN" },
{id: "8", name: "vwx", gender: "m", age:"78", country:"USA" },
]
As well as an array containing the keys of interest:
wantedKeys = ["name", "age", "country"]
Desired outcome:
peopleFiltered = [
{name: "abc", age:"15", country:"USA" },
{name: "def", age:"25", country:"BRA" },
{name: "ghi", age:"05", country:"CHI" },
{name: "jkl", age:"35", country:"RUS" },
{name: "mno", age:"41", country:"JAP" },
{name: "pqr", age:"30", country:"COL" },
{name: "stu", age:"31", country:"CAN" },
{name: "vwx", age:"78", country:"USA" },
]
How can we filter the people
array to generate a new array with only the elements specified in the wantedKeys
array?