【问题标题】:Javascript: Get all objects by specific fieldJavascript:按特定字段获取所有对象
【发布时间】:2014-05-16 20:41:19
【问题描述】:

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

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

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 之类的函数来完成它,而无需编写长函数?

【问题讨论】:

    标签: javascript arrays node.js performance


    【解决方案1】:

    是的,很简单:

    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');
    

    【讨论】:

      【解决方案2】:

      Underscore.js(您可以作为节点包安装)有一个名为 _.pluck 的函数,它正是这样做的。如果你 _ = require("underscore") 你实际上可以用 _.pluck 替换 magicFunction

      【讨论】:

        【解决方案3】:

        @p.s.w.g 可能是您正在寻找的解决方案,但我想展示另一个解决方案:使用 core.operators

        var names = users.map(opts.get('name'));
        

        【讨论】:

          猜你喜欢
          • 2018-08-19
          • 2019-03-24
          • 1970-01-01
          • 2017-06-09
          • 1970-01-01
          • 2012-03-18
          • 2010-11-08
          • 2017-06-07
          • 2020-07-23
          相关资源
          最近更新 更多