Home > OS >  compare array of object with array of object in javascript
compare array of object with array of object in javascript

Time:12-01

compare array of object with array of keys, filter array of object with array keys.

Input:

let a = ['aa'];
let b = [{ aa: 1, bb: 2, c: 30 },{ aa: 2, bb: 3, c: 40}];

output:

b = [{bb: 2, c: 30 },{bb: 3, c: 40}];

original array should be mutate.

CodePudding user response:

Much similiar to @SachilaRanawaka 's answer, but works without modifying the original b array:

let a = ['aa'];
let b = [{ aa: 1, bb: 2, c: 30 },{ aa: 2, bb: 3, c: 40}];

function removeKey(obj, key) {
  let clone = Object.assign({}, obj); // <-- shallow clone
  if (key in clone) {
    delete clone[key];
  }
  return clone;
}

function removeKeys(keys, objs) {
  return objs.map(o => keys.reduce(removeKey, o));
}

console.log(removeKeys(a, b));

CodePudding user response:

You could take a destructuring with getting the rest approach.

This approach does not mutate the original data.

const
    unwanted = ['aa'],
    data = [{ aa: 1, bb: 2, c: 30 }, { aa: 2, bb: 3, c: 40 }],
    result = data.map(o => unwanted.reduce((q, k) => {
        const { [k]: _, ...r } = q;
        return r;
    }, o));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

It can probably be solved with less lines of code, but this was the first i could think of.

let keysToRemove = ['aa'];
let array = [{ aa: 1, bb: 2, c: 30 },{ aa: 2, bb: 3, c: 40}];
let result = array.map((item) => {
  let filtered = Object.keys(item)
    .filter((key) => !keysToRemove.includes(key))
    .reduce((obj, key) => {
      obj[key] = item[key];
      return obj;
    }, {});
  return filtered;
});
console.log(result);

CodePudding user response:

use the map operator and use delete to delete properties from the object

let a = ['aa'];
let b = [{ aa: 1, bb: 2, c: 30 },{ aa: 2, bb: 3, c: 40}];


const result = b.map(item => {

    Object.keys(item).forEach(key => {
       if(a.includes(key)){
          delete item[key]
       }
    })
    
    return item
  
})

console.log(result)

  • Related