当您使用lodash合并两个对象时,如何筛选属性名称

时间:2017-01-27 04:56:37

标签: javascript object merge lodash

我正在尝试使用lodash合并两个对象,并根据源属性条件对属性名称执行过滤,但源属性名称是结果中的mangles。过滤器似乎不适用于对象属性名称。

result = _.merge(library, 
  _.filter(inbasket, function(book) {
    return parseFloat(book.rating) > 3.9;
  })

https://jsfiddle.net/shirha/d1j1yq4w/

2 个答案:

答案 0 :(得分:2)

而不是_.filter使用_.pickBy作为对象

result = _.merge(
    library, 
    _.pickBy(inbasket, function(book) {
        return parseFloat(book.rating) > 3.9;
    }
)

答案 1 :(得分:1)

在对象上使用_.filter时,返回的值是一个数组。所以你试图将一个数组合并到一个对象中。该数组在技术上也是一个对象,但键是0,1,2 ......因此您仍然可以将该数组与该对象合并,但原始键将丢失。这是您的_.filter操作产生的结果:

var library = {
  0942815367: {
    name: "Using SQLite",
    pub: "OReilly",
    year: 2010,
    rating: "3.9"
  },
  9238614075: {
    name: "HTML5 Canvas",
    pub: "OReilly",
    year: 2013,
    rating: "4.3"
  },
  4239867510: {
    name: "Essential GWT",
    pub: "Aw",
    year: 2011,
    rating: "2.6"
  }
},
inbasket = {
  6029738154: {
    name: "HTML5 Hacks",
    pub: "OReilly",
    year: 2012,
    rating: "4.5"
  },
  3901825674: {
    name: "Pro Django 2e",
    pub: "Apress",
    year: 2013,
    rating: "4.0"
  },
  4381529067: {
    name: "GWT in Action",
    pub: "Manning",
    year: 2007,
    rating: "3.7"
  },
  3014972685: {
    name: "Learning Node",
    pub: "OReilly",
    year: 2012,
    rating: "3.5"
  }
};

var result = _.cloneDeep(library);

for(var bookKey in inbasket) {
    if(Number(inbasket[bookKey]['rating']) > 3.9) {
      result[bookKey] = inbasket[bookKey];
    }
}

document.getElementById('result').innerHTML = 
JSON.stringify(result, undefined, 2);

这是一个解决方案:emitEvent: false

select top 1 distinct y from x order by count(*) over (partition by y) desc