如何确定一个数组中的对象是否也存在于另一个数组中

huangapple go评论57阅读模式
英文:

How to find out if an object from an array is present also in another array

问题

以下是代码部分的中文翻译:

var array1 = {"id":"car", "name":"honda", "virtues":[{"price":99}, {"size" : ""}, {"condition" : "new"}};

var array2 = {'userid' : '2', 'username' : 'john','prefs' : [{"price":1}]};

我不关心大小我只想要价格和条件所以我想找出它们是否也存在于array2中所以我这样做

calceffect = function(myarray) {
 myarray.map(x => {
  for(let key in x) {
   if(key!= 'size') {
    array2.prefs.map(d => 
     {
      for(let k in d) {
       if(k == key){
        console.log('present');
       } else {
        console.log('absent');
       }
      }
     }
    );
   }
  }
 });
}

calceffect(array1.virtues); //在这种情况下,它将输出'it is present' for "price"和'absent' for "condition"

它按预期工作但我觉得它有点复杂有没有更简洁的方法获得相同的结果

谢谢
英文:

Hi,

I have 2 objects that contain arrays of objects within like this:

var array1 = {"id":"car", "name":"honda", "virtues":[{"price":99}, {"size" : ""}, {"condition" : "new"}]};

var array2 = {'userid' : '2', 'username' : 'john','prefs' : [{"price":1}]};

I dont care for size all I want is price and condition so I want to find out if those are present also in array2 so I did this:

calceffect = function(myarray) {
 myarray.map(x => {
  for(let key in x) {
   if(key!= 'size') {
    array2.prefs.map(d => 
     {
      for(let k in d) {
       if(k == key){
        console.log('present');
       } else {
        console.log('absent');
       }
      }
     }
    );
   }
  }
 });
}

calceffect(array1.virtues); //in this case it will output 'it is present' for "price" and 'absent' for "condition"

it works as expected, however I find it like a little too convoluted. Is there a cleaner way to get the same result?

Thank you.

答案1

得分: 2

你可以获取键、计数并获得结果。

英文:

You could get the keys, count and get the result

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const
    getKeys = a =&gt; a.flatMap(o =&gt; Object.keys(o)),
    a = { id: &quot;car&quot;, name: &quot;honda&quot;, virtues: [{ price: 99 }, { size: &quot;&quot; }, { condition: &quot;new&quot; }] },
    b = { userid: &#39;2&#39;, username: &#39;john&#39;, prefs: [{ price: 1 }] },
    add = (object, d) =&gt; v =&gt; object[v] = (object[v] || 0) + d,
    counts = {}
    result = { common: [], unique: [] };

getKeys(a.virtues).forEach(add(counts, 1));
getKeys(b.prefs).forEach(add(counts, -1));

Object.entries(counts).forEach(([k, v]) =&gt; result[v ? &#39;unique&#39; : &#39;common&#39;].push(k));

console.log(result);

<!-- end snippet -->

答案2

得分: 1

这是您要翻译的内容:

有一种方法可以使用内置的 JavaScript 方法 `filter`  `some`来检查 `price`  `condition` 属性是否在 `array2.prefs` 

一种重构的方法是创建一个返回布尔值的函数

let array1 = {"id":"car", "name":"honda", "virtues":[{"price":99}, {"size" : ""}, {"condition" : "new"}]};

let array2 = {'userid' : '2', 'username' : 'john','prefs' : [{"price":1}]};

首先我们过滤掉`array1.virtues`中具有价格或条件的对象其次我们使用 `every` 方法来检查所有对象是否满足这样的条件`array.prefs` 中至少存在一个对象该对象同时具有 `price`  `condition`我们使用 `some` 方法来检查是否存在这样的对象

let priceAndCondition = array1.virtues.filter(x => x.price || x.condition).every(x => array2.prefs.some(y => y.price && y.condition));

console.log(priceAndCondition);

希望这对您有所帮助。

英文:

there is a way that you can use the built in JavaScript methods such as filter and some to check if the price and condition properties are in array2.prefs.

One way you could refactor this is making a function that returns a boolean:

let array1 = {&quot;id&quot;:&quot;car&quot;, &quot;name&quot;:&quot;honda&quot;, &quot;virtues&quot;:[{&quot;price&quot;:99}, {&quot;size&quot; : &quot;&quot;}, {&quot;condition&quot; : &quot;new&quot;}]};

let array2 = {&#39;userid&#39; : &#39;2&#39;, &#39;username&#39; : &#39;john&#39;,&#39;prefs&#39; : [{&quot;price&quot;:1}]};

First we filter out the objects in array1.virtues that have a price or condition, secondly we use the every method to check if all objects satisfy the condition that there exists at least one object in array.prefs that has both a price and a condition. some method is used to check for the existing object.

let priceAndCondition = array1.virtues.filter(x =&gt; x.price || x.condition).every(x =&gt; array2.prefs.some(y =&gt; y.price &amp;&amp; y.condition));

console.log(priceAndCondition);

答案3

得分: 0

以下是已翻译的代码部分:

// 使用以下代码可以实现这一目标 - 

// 创建一个所需键的数组以进行检查
const desiredKeys = ['price', 'condition'];

// 检查每个所需键是否存在于array2的prefs中
const presentKeys = desiredKeys.filter(key => array2.prefs.some(pref => 
pref.hasOwnProperty(key)));

// 输出结果
presentKeys.forEach(key => console.log(`${key} is present`));

如果要使用不希望的键的数组可以使用以下代码 - 

// 创建一个不希望的键的数组以进行检查
const unDesiredKeys = ['size'];

// 检查每个所需键是否存在于array2的prefs中
const presentKeys = unDesiredKeys.filter(key => 
      array2.prefs.some(pref => !pref.hasOwnProperty(key)));

// 输出结果
presentKeys.forEach(key => consolesole.log(`${key} is present`));
英文:

You can achieve it by using below code -

// create an array of the desired keys to check
const desiredKeys = [&#39;price&#39;, &#39;condition&#39;];

// check if each desired key is present in array2 prefs
const presentKeys = desiredKeys.filter(key =&gt; array2.prefs.some(pref =&gt; 
pref.hasOwnProperty(key)));

// output the result
presentKeys.forEach(key =&gt; console.log(`${key} is present`));

If you want to use array of undesired keys, then you can use below code -

// create an array of the desired keys to check
const unDesiredKeys = [&#39;size&#39;];

// check if each desired key is present in array2 prefs
const presentKeys = unDesiredKeys.filter(key =&gt; 
      array2.prefs.some(pref =&gt; !pref.hasOwnProperty(key)));

// output the result
presentKeys.forEach(key =&gt; console.log(`${key} is present`));

答案4

得分: 0

这是好的吗?

var array1 = {
    "id": "car",
    "name": "honda",
    "virtues": [{"price": 99}, {"size": ""}, {"condition": "new"}]
};

var array2 = {
    'userid': '2',
    'username': 'john',
    'prefs': [{"price": 1}]
};

const value1 = Object.values(array1);
const value2 = Object values(array2);
const vObj1 = value1.filter(item => typeof item === "object");
const vObj2 = value2.filter(item => typeof item === "object");
const obj1 = vObj1[0];
const obj2 = vObj2[0];

for (let index of obj1) {
    for (let index2 of obj2) {
        console.log(Object.keys(index2).filter(test => test === Object.keys(index)[0]));
    }
}
英文:

this is good?

var array1 = {
    &quot;id&quot;:&quot;car&quot;,
    &quot;name&quot;:&quot;honda&quot;,
    &quot;virtues&quot;:[{&quot;price&quot;:99}, {&quot;size&quot; : &quot;&quot;}, {&quot;condition&quot; : &quot;new&quot;}]
};

var array2 = {
    &#39;userid&#39; : &#39;2&#39;,
    &#39;username&#39; : &#39;john&#39;,
    &#39;prefs&#39; : [{&quot;price&quot;:1}]
};

const value1 = Object.values(array1);
const value2 = Object.values(array2);
const vObj1 = value1.filter(item =&gt; typeof item === &quot;object&quot;);
const vObj2 = value2.filter(item =&gt; typeof item === &quot;object&quot;);
const obj1 = vObj1[0];
const obj2 = vObj2[0];

for(let index of obj1){
    for(let index2 of obj2){
    console.log(Object.keys(index2).filter(test =&gt; test ===  Object.keys(index)[0]));
    }
}

huangapple
  • 本文由 发表于 2023年2月24日 01:36:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定