gpt4 book ai didi

javascript - 根据另一个包含 javascript 键的数组过滤对象数组

转载 作者:行者123 更新时间:2023-12-01 16:25:47 25 4
gpt4 key购买 nike

我有一个对象数组,如下所示:

people = [
{id: "1", name: "abc", gender: "m", age:"15" },
{id: "2", name: "a", gender: "m", age:"25" },
{id: "3", name: "efg", gender: "f", age:"5" },
{id: "4", name: "hjk", gender: "m", age:"35" },
{id: "5", name: "ikly", gender: "m", age:"41" },
{id: "6", name: "ert", gender: "f", age:" 30" },
{id: "7", name: "qwe", gender: "f", age:" 31" },
{id: "8", name: "bdd", gender: "m", age:" 78" },
]

我还有另一个数组,其中包含我希望从对象中获得的值:

filter = ['name','age']

我想过滤人员数组以返回仅包含该过滤器中的值的对象数组。所以输出应该是这样的:

    people = [
{ name: "abc", age:"15" },
{ name: "a", age:"25" },
{ name: "efg", age:"5" },
{ name: "hjk", age:"35" },
{ name: "ikly", age:"41" },
{ name: "ert", age:" 30" },
{ name: "qwe", age:" 31" },
{ name: "bdd", age:" 78" },
]

这类似于此处的问题:filtering an array of objects based on another array in javascript

最佳答案

您可以映射对象并获取新条目的键。

var people = [{ id: "1", name: "abc", gender: "m", age: "15" }, { id: "2", name: "a", gender: "m", age: "25" }, { id: "3", name: "efg", gender: "f", age: "5" }, { id: "4", name: "hjk", gender: "m", age: "35" }, { id: "5", name: "ikly", gender: "m", age: "41" }, { id: "6", name: "ert", gender: "f", age: " 30" }, { id: "7", name: "qwe", gender: "f", age: " 31" }, { id: "8", name: "bdd", gender: "m", age: " 78" }],
keys = ['name', 'age'],
result = people.map(o => Object.fromEntries(keys.map(k => [k, o[k]])));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 根据另一个包含 javascript 键的数组过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61886260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com