【问题标题】:FIltering out entries with a property using Lodash使用 Lodash 过滤带有属性的条目
【发布时间】:2020-07-24 19:41:09
【问题描述】:

在我的 React 应用程序中,我有一个函数,它将两个数组合并在一起,我目前正在使用 lodash 库和 unionBy 函数

到目前为止,这是我的代码:

export function generateDisplayedLabels(systemLabels, masterState){
  const mappedSystemlabels = systemLabels.map(label => Object.assign(label, {type: "system"}))
  const mappedMasterState = masterState.map(label => Object.assign(label, {type: "master"}))
  const displayedLabels = _.unionBy(mappedSystemlabels, mappedMasterState, 'geometry');
  return displayedLabels
}

基本上我标记了两个单独的数组,然后尝试在它们的geometry 对象上过滤它们。

但在最终结果中,我看到条目具有重复条目(我认为这可能是因为它不像“unionBy”复杂对象那样容易。

这是一个例子。

[{ data: {...},
   geometry: {height: 1.24703087885986
type: "RECTANGLE"
width: 60.25210084033614
x: 30.952380952380953
y: 87.50989707046713
}, 
type: "master" },
data: {...},
   geometry: {height: 1.24703087885986
type: "RECTANGLE"
width: 60.25210084033614
x: 30.952380952380953
y: 87.50989707046713
}, 
type: "" }

这导致两个条目仍然在新数组中。

理想情况下,我想根据几何对象进行过滤,如果两者都存在,则应优先使用 {type: master} 的那个

有人可以帮我在现有函数中实现这个逻辑吗?

【问题讨论】:

标签: javascript lodash


【解决方案1】:

使用reduce

注意:为了比较JSON.stringify(item.geometry) === JSON.stringify(cur.geometry),几何中的属性必须是相同的顺序。

let mappedMasterState = [{ 
  geometry: {
      height: 1.24703087885986,
      type: "RECTANGLE",
      width: 60.25210084033614,
      x: 30.952380952380953,
      y: 87.50989707046713,
  }, 
  type: "master" }
];
let mappedSystemlabels = [{
  geometry: {
    height: 1.24703087885986,
    type: "RECTANGLE",
    width: 60.25210084033614,
    x: 30.952380952380953,
    y: 87.50989707046713,
  }, 
  type: "" }
];



let displayedLabels = [...mappedMasterState, ...mappedSystemlabels];

displayedLabels = displayedLabels.reduce((acc, cur) => {  
  const isExists = acc.find( (item, index) => JSON.stringify(item.geometry) === JSON.stringify(cur.geometry));
  if(isExists && isExists.type === "master") return acc;    
  
  else if (isExists) acc.splice(acc.indexOf(isExists), 1);              
  acc.push(cur);
  return acc;
}, [])

console.log(displayedLabels)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2017-01-10
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    相关资源
    最近更新 更多