gpt4 book ai didi

Javascript:按特定字段获取所有对象

转载 作者:行者123 更新时间:2023-11-30 12:43:01 24 4
gpt4 key购买 nike

这可能是一个很简单的问题,但我还没有遇到一个优雅的解决方案。

如何通过单个字段从数组中获取所有对象。例如;


var users = [{name:'John', age: 20},
{name:'Sarah', age: 21},
{name:'George', age:34}];
var names = magicFunction(users, 'name');
// names = ['John', 'Sarah', 'George'];
// Another challenge is not to get field name (in this case 'name') with the value

我想知道您是否可以在不编写长函数的情况下使用 filtermap 之类的函数来做到这一点?

最佳答案

是的,它非常简单:

var prop = 'name';
var names = users.map(function(x) { return x[prop]; });

或者如果你想把它写成一个函数:

function getProp(arr, prop)
{
return arr.map(function(x) { return x[prop]; });
}

var names = getProp(users, 'name');

更新 在 ES6 语法中:

const getProp = (arr, prop) => Array.prototype.map.call(arr, x => x[prop]);
const names = getProp(users, 'name');

关于Javascript:按特定字段获取所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23704224/

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