在javascript中返回2个对象之间的匹配元素数组的最高效方法是什么?

给定 javascript 中的以下 2 个对象:


myFruit = {

 'apple': 14,

 'orange': 3,

 'pear': 10

}


theirFruit = {

 'banana': 10,

 'grape': 30,

 'apple': 2

}

返回匹配元素数组的最高效方式是什么?每个键的值无关紧要。


下面是一个例子,但有些事情告诉我可能有更好的方法。


let matches = [];


let myKey;


Object.keys(myFruit).forEach((key, index) => {

  myKey = key;

  Object.keys(theirFruit).forEach((theirKey, index) => {

    if(myKey === theirKey) {

       matches.push(theirKey);

    }

  });

});


console.log(matches);

// will print: ['apple']


console.log(matches.length);

// will print: 1


茅侃侃
浏览 141回答 3
3回答

慕尼黑8549860

这是我的解决方案。const matches = Object.keys(myFruit).filter(key => key in theirFruit);  console.log(matches); // will output ['apple']

当年话下

2 个对象是否包含匹配键如果所有键都不同,则合并的对象将具有与每个对象一样多的键。let haveAMatchingKey = Object.keys(Object.assign({}, myFruit, theirFruit)).length !=    Object.keys(myFruit).length + Object.keys(theirFruit)编辑后:返回匹配元素数组的最高效方式?let myFruitSet = new Set(Object.keys(myFruit));let theirFruitKeys = Object.keys(theirFruit);let matchingKeys = theirFruitKeys.filter(fruit => myFruitSet.has(fruit))

牧羊人nacy

使用HashMap数据结构方法:const findCommonFruits = () => {&nbsp; &nbsp; const myFruit = {&nbsp; &nbsp; 'apple': 14,&nbsp; &nbsp; 'orange': 3,&nbsp; &nbsp; 'pear': 10&nbsp; &nbsp; }&nbsp; &nbsp; const theirFruit = {&nbsp; &nbsp; 'banana': 10,&nbsp; &nbsp; 'grape': 30,&nbsp; &nbsp; 'apple': 2&nbsp; &nbsp; }&nbsp; &nbsp; // #1 select lowest object keys&nbsp; &nbsp; let lowestObj = null;&nbsp; &nbsp; let biggestObj = null;&nbsp; &nbsp; if (Object.keys(myFruit).length < Object.keys(theirFruit).length) {&nbsp; &nbsp; &nbsp; &nbsp; lowestObj = myFruit;&nbsp; &nbsp; &nbsp; &nbsp; biggestObj = theirFruit;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; lowestObj = theirFruit;&nbsp; &nbsp; &nbsp; &nbsp; biggestObj = myFruit;&nbsp; &nbsp; }&nbsp; &nbsp; // 2 Define an actual hashmap that will holds the fruit we have seen it&nbsp; &nbsp; const haveYouSeenIt = {};&nbsp; &nbsp; for (let fruit of Object.keys(lowestObj)) {&nbsp; &nbsp; &nbsp; &nbsp; haveYouSeenIt[fruit] = fruit;&nbsp; &nbsp; }&nbsp; &nbsp; const res = [];&nbsp; &nbsp; for (let fruit of Object.keys(haveYouSeenIt)) {&nbsp; &nbsp; &nbsp; &nbsp; if (biggestObj[fruit] !== undefined) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.push(fruit);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return res;}console.log(findCommonFruits()); // ['apple']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript