使用es6从两个对象获取差异对象 [英] getting difference object from two objects using es6

查看:836
本文介绍了使用es6从两个对象获取差异对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出使用es6在两个对象之间获取相交对象的最佳方法是什么. 我的意思是这样的:

Im trying to figure out whats the best way to get an intersection object between two objects using es6. by this i mean something like:

a = {a:'a',b:'b',c:'c', d:'d'};
b = {a:'a',b: '1', c:'c', d:'2', f'!!!'}
// result I want:
c = getDifference(a,b)
//c is now: {b:'1', d:'2'}

是否有使用es6进行此操作的简短方法,还是我需要使用for(in)与Object.keys()进行对象迭代并进行比较,并将交集分配给c?

Is there a short way to do this using es6, or do I need to iterate over the a object using for(in) with Object.keys() and compare, assigning intersections to c?

(a,b) => {
    const c = {};
    for(const _key in Object.keys(a)){
       if(b[_key] && b[_key] !== a[_key]){
           c[_key] = b[_key];
       }
    }
    return c;
}

我知道loadash/underscore具有这类帮助函数...但是尝试查看es6是否为此具有任何新的短语法,如果没有,使用香草js进行此操作的最短方法是什么.

I know loadash/underscore has these kinds of helper functions... but trying to see if es6 has any new short syntax for this, and if not whats the shortest way to do this using vanilla js.

推荐答案

您可以使用Object.entries()获取对象b的条目,然后使用.filter()过滤掉相同的键/值对,然后,您可以像这样使用Object.fromEntries()重建对象:

You can get the entries of object b using Object.entries() and then filter out the key-value pairs which are the same using .filter(), then, you can rebuild your object using Object.fromEntries() like so:

const a = {a:'a',b:'b',c:'c', d:'d'};
const b = {a:'a',b: '1', c:'c', d:'2', f:'!!!'}

const getDifference = (a, b) => 
  Object.fromEntries(Object.entries(b).filter(([key, val]) => key in a && a[key] !== val));


// result I want:
const c = getDifference(a,b); // peforms b-a (but only gives properties from both a and b)
console.log(c); // {b:'1', d:'2'}

但是,Object.fromEntries()当前处于草稿模式,因此您可以改用.reduce():

However, Object.fromEntries() is currently in draft mode, and so you may use .reduce() instead:

const a = {a:'a',b:'b',c:'c', d:'d'};
const b = {a:'a',b: '1', c:'c', d:'2', f:'!!!'}

const getDifference = (a, b) => 
  Object.entries(b).filter(([key, val]) => a[key] !== val && key in a).reduce((a, [key, v]) => ({...a, [key]: v}), {});


// result I want:
const c = getDifference(a,b); // peforms b-a (but only gives properties from both a and b)
console.log(c); // {b:'1', d:'2'}

这篇关于使用es6从两个对象获取差异对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆