【问题标题】:Get data based on field, which is evaluated on condition根据字段获取数据,根据条件进行评估
【发布时间】:2017-04-24 01:12:00
【问题描述】:

我有如下对象数组:

var data = [
    { SrNo: 1, BabyName: 'A', ParentName: 'X' },
    { SrNo: 2, BabyName: 'D', ParentName: 'X' },
    { SrNo: 3, BabyName: 'B', ParentName: 'Y' },
    { SrNo: 4, BabyName: 'E', ParentName: 'Y' },
    { SrNo: 5, BabyName: 'C', ParentName: 'Z' }
]

我得到BabyNames 数组的输入,我必须为它们找到ParentNames,然后过滤ParentNames 上的数据作为输出。

输入 = ['A','B'];

所以,如果我的输入是 ['A','B'],我的预期输出是 4 个对象的数组 (SrNo 1,2,3,4)

我做了什么来实现

//filter all objects for matching BabyNames
var a1 = _.filter(data, function (item) { return _.contains(input, item["BabyName"]); })

//pluck ParentNames from a1 array of objects and take unique
var a2 = _.uniq(_.pluck(a1,"ParentName"))

//filter all objects (original data set) on ParentName with a2 as input
var a3 = _.filter(data, function (item) { return _.contains(a2, item["ParentName"]); })

我发现这不是一种有效的方法,但无法找到任何其他解决方案。 请指导。

【问题讨论】:

  • SrNo 是否从 BabyName 继承对象属性,而 BabyName 是从 parentName 继承属性?不知道如何阅读上面的对象图。
  • “对象数组如下”,那不是对象数组。请附上minimal reproducible example
  • 我已经添加了输入数据变量
  • 基本上你需要迭代数据数组至少 2 次,一次用于获取父母,一次用于过滤结果。如果您使用Set 或对象作为哈希表,您可以克服中间步骤。

标签: javascript arrays json underscore.js filtering


【解决方案1】:

基本上,您需要对数据数组进行至少 2 次迭代,一次用于获取父母,一次用于过滤结果。如果您使用Set 或对象作为哈希表,您可以克服中间步骤。

这是 ES6 中的提议。

var data = [{ SrNo: 1, BabyName: 'A', ParentName: 'X' }, { SrNo: 2, BabyName: 'D', ParentName: 'X' }, { SrNo: 3, BabyName: 'B', ParentName: 'Y' }, { SrNo: 4, BabyName: 'E', ParentName: 'Y' }, { SrNo: 5, BabyName: 'C', ParentName: 'Z' }],
    input = ['A', 'B'],
    babies = new Set(input),
    parents = new Set,
    result;

data.forEach(a => babies.has(a.BabyName) && parents.add(a.ParentName));
result = data.filter(a => parents.has(a.ParentName));

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

【讨论】:

    【解决方案2】:

    Here is another way 得到结果。

    var input = ['A', 'B'];
    
    function getParents(input, filterProp, returnProp) {
      var filtered = data.filter(function(d) {
        return input.indexOf(d[filterProp]) !== -1;
      });
      if (returnProp) {
        return filtered.map(function(d) {
          return d[returnProp];
        });
      }
      return filtered;
    }
    
    // get the result by first filter with baby name and return parent names
    // then filter with parent names
    getParents(getParents(input, "BabyName", "ParentName"), "ParentName");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多