更新具有匹配属性的对象并忽略新属性 [英] Update an object with matching properties and ignore new properties

查看:139
本文介绍了更新具有匹配属性的对象并忽略新属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Typescript,我想用另一个更新对象,只在匹配的键上。

I'm using Typescript and I would like to update an object with another, only on the matching keys.

// Destination
objectOne = {
  a: 0,
  b: 0,
};

// Source
objectTwo = {
  a: 1,
  b: 1,
  c: 1,
};

// Expected
result = {
  a: 1,
  b: 1,
};

// Current solution
const current = {};
Object.keys(objectTwo).forEach(key => key in objectOne ? current[key] = objectTwo[key] : null);

console.log(current);

是否存在单行 (即不是遍历键的自定义函数) 会忽略源中的属性 c 吗?我还想避免使用诸如lodash或JQuery之类的库。

is there a one-liner (i.e. not a custom function that iterates over the keys) that would ignore the property c in the source ? I would also like to avoid using libraries such as lodash or JQuery.

重复编辑我的问题不是关于合并两个对象,我的问题是忽略第二个对象中的字段,这不是在第一个对象中。

Duplicate EDIT my question isn't about merging two objects, my question is about ignoring the fields in the second object, that aren't in the first object.

推荐答案

过了一会儿没有答案,似乎最短的解决方案就是我自己提供的解决方案:

After a while without answers, it seems the shortest solution is the one I provided myself :

Object.keys(newObj).forEach(key => key in oldObj? result[key] = newObj[key] : null)

这篇关于更新具有匹配属性的对象并忽略新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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