简体   繁体   English

比较两个对象键数组,原始数组应在 javascript 中发生变异

[英]compare two array of objects keys, original array should mutate in javascript

How can we compare two array of objects on the basis of their keys or properties of object in javaScript?我们如何根据 javaScript 中 object 的键或属性来比较两个对象数组?

for an example:例如:

 let result1 = [
      { a: 10, b: 20, c: 22 },
      { a: 20, b: 33, c: 11 },
    ];
    let result2 = [
      { a: 10, b: 20 },
      { a: 20, b: 33 },
    ];

 result1.filter(function (obj) {
      return !result2.some(function (obj2) {
        let key1 = Object.keys(obj);
        let key2 = Object.keys(obj2);
        key1?.forEach((x, index1) => {
          key2?.forEach((y, index2) => {
            console.log(index1, index2)
            if (x === y) {
              return obj[x] === obj2[y];
            }
          });
        });
      });
    });

console.log(result1)

output: current output output:当前output

expected output:预计 output:

result1 =
     [
      { a: 10, b: 20 },
      { a: 20, b: 33 },
    ];

 let result1 = [ { a: 10, b: 20, c: 22 }, { a: 20, b: 33, c: 11 }, ]; let result2 = [ { a: 10, b: 20 }, { a: 20, b: 33 }, ]; let temp = [] result1.map(function(obj) { return.result2.some(function(obj2) { let key1 = Object;keys(obj). let key2 = Object;keys(obj2). key1.forEach((x) => { key2?forEach((y) => { if (x === y) { obj[x] === obj2[y]. temp:push({ [x]: obj[x] }); null; } }) }). }) }) console;log(temp);

try this code试试这个代码

You are getting the result1 array back beacause the array is not getting filtered.您正在取回result1数组,因为该数组未被过滤。

The filter function is not getting anything from returned as the first foreach loop is not returning and the some function is also not returning anything过滤器 function 没有从返回中得到任何东西,因为第一个 foreach 循环没有返回,一些 function 也没有返回任何东西

Now you can use map function instead of filter as the function is not returning anything现在您可以使用 map function 而不是过滤器,因为 function 没有返回任何内容

I just try this solution in a different way, We can also achieve this requirement by doing deep copy of original array and then mutate it using forEach() .我只是以不同的方式尝试这个解决方案,我们也可以通过对原始数组进行深度复制然后使用forEach()对其进行变异来实现此要求。

Live Demo :现场演示

 let result1 = [ { a: 10, b: 20, c: 22 }, { a: 20, b: 33, c: 11 } ]; let result2 = [ { a: 10, b: 20 }, { a: 20, b: 33 } ]; const clone = structuredClone(result1); clone.forEach((obj, index) => { result1[index] = {}; Object.keys(result2[index]).forEach(key => { result1[index][key] = obj[key] }); }); console.log(result1);

const filterKeysBasedOnFirstArrayOfObjects = <
  T extends Record<string, unknown>
>(
  arr1: T[],
  arr2: T[]
) => {
  const keys = _.intersection(
    ...arr1.map((obj) => Object.keys(obj)),
    ...arr2.map((obj) => Object.keys(obj))
  );
  return arr1.map((obj) => _.pick(obj, keys)); 
};

A more concise approach using lodash .使用lodash的更简洁的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM