【问题标题】:Most efficient way to search through an object and array locating match搜索对象和数组定位匹配的最有效方法
【发布时间】:2016-06-09 06:59:00
【问题描述】:

我有 2 个对象/数组:

var objA = {
    Red Chair : "DC10291",
    USBDongle : "USKI82322",
}

var arrayB = [
   {
       field: "Yellow Banana",
       id: "Yellow Banana"
   },
   {
       field: "Red Chair",
       id: "Red Chair"
   },
   {
       field: "Garden",
       id: "Garden"
   }
]

我想做的是,如果来自objAKEY,例如Red Chair,存在于arrayB 中,然后将其从arrayB 中删除。

我已经这样做了:

var arrayClone = _.cloneDeep(arrayB);
var removeThese = [];

Object.keys(arrayClone).forEach(function(p) {
    removeThese.push(p)
});


removeThese.forEach(function(remove) {
    arrayB.forEach(function(item) {
        if(item.id === remove) {
            delete objA[remove];
        }
    });
 });

上述工作按预期工作,但是这是最有效的吗?我问的原因是因为在数组循环中循环遍历和数组感觉不是最佳实践?并且会对性能产生影响

【问题讨论】:

  • 您希望arrayB 数组保持不变并从objA 中删除匹配的属性吗?

标签: javascript arrays javascript-objects lodash


【解决方案1】:

你可以像这样简单地过滤它

_.filter(arrayB, obj => !objA.hasOwnProperty(obj.field))
// [ { field: 'Yellow Banana', id: 'Yellow Banana' },
//  { field: 'Garden', id: 'Garden' } ]

这使用 ES2015 的箭头函数语法。您可以使用这样的普通函数编写相同的代码

arrayB.filter(function(obj) {
  return !objA.hasOwnProperty(obj.field);
});
// [ { field: 'Yellow Banana', id: 'Yellow Banana' },
//  { field: 'Garden', id: 'Garden' } ]

我们基本上过滤掉了所有field 值是objA 中的键的对象。

【讨论】:

  • 谢谢,对不起,这是新的……过滤后如何删除?
  • @OamPsy 你的意思是,你还想从arrayB 中删除值?
  • 对不起,我的意思是我怎样才能从 objA 中删除匹配项
  • @OamPsy 就是这样,对吧...查看代码 cmets 中的示例输出
  • 好的,但是在你上面的例子中......我知道 arrayb 和 objA 来自哪里,但是 obj 呢?
【解决方案2】:

如果您想保留原始数组 B 并根据您的情况获得它的简化版本,那么 Array.prototype.reduce() 会以 O(n) 时间复杂度来实现。但是,如果您想就地执行此操作,那么 Array.prototype.reduceRight() 会以 O(n) 的时间复杂度进行。

var objA = {
    "Red Chair" : "DC10291",
    "USBDongle" : "USKI82322",
},

 arrayB = [
   {
       field: "Yellow Banana",
       id: "Yellow Banana"
   },
   {
       field: "Red Chair",
       id: "Red Chair"
   },
   {
       field: "Garden",
       id: "Garden"
   }
],

 arrayC = arrayB.reduce((p,c) => !objA[c.field] ? p.concat(c) : p, []);
 console.log(arrayC);
 arrayB.reduceRight((p,c,i,a) => (p[c.field] && a.splice(i,1),p),objA);
 console.log(arrayB);

【讨论】:

    猜你喜欢
    • 2014-10-31
    • 2011-06-06
    • 2023-01-10
    • 1970-01-01
    • 2012-05-20
    • 2014-05-24
    • 1970-01-01
    • 2021-10-08
    • 2015-01-01
    相关资源
    最近更新 更多