简体   繁体   English

分配目标和源中交集的键值的最快方法 object

[英]quickest way to assign values of keys which are intersection in the target and source object

I want to assign only those keys which are already present in the target object and not the other keys that are done by the object.assign method.我只想分配目标 object 中已经存在的那些键,而不是 object.assign 方法完成的其他键。

example
a = { x: 2}
b = {x:3, y:4}

then result = {x:3}

I know there are other ways in past but is there any newer and better ways to do this like in one line?我知道过去还有其他方法,但是有没有更新更好的方法来做到这一点?

You can reduce the keys of the target object to a new object by taking the values from the obj if they exist:您可以通过从obj中获取值(如果存在)来将target object 的键减少为新的 object:

 const fn = (target, obj) => Object.keys(target).reduce((acc, key) => key in obj? {...acc, [key]: obj[key] }: acc, {}) const a = { x: 2} const b = { x:3, y:4 } const result = fn(a, b) console.log(result)

I think the fastest way is:我认为最快的方法是:

for (let key in b) {
  if (a[key] === undefined) {
    delete b[key];
  }
}

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

相关问题 Javascript只分配源到目标对象的交集 - Javascript assign only intersection of source to target object 检查对象内哪个属性具有值的最快方法? - Quickest way to check which property inside an object holds value? 从 AngularJS 中的对象访问所有嵌套值的最快方法 - Quickest way to access all nested values from object in AngularJS 如何为具有相似键的对象分配值? - How to assign values to object that has similar keys? JS将带有对象值的数组分配给对象键 - JS assign array with objects values to object keys 如何在目标数组值内匹配javascript源数组键 - How to match javascript source array keys within target array values 识别数组中具有与另一个对象数组中的属性唯一的属性的对象的最快方法 - quickest way to identify objects in array which have properties that are unique from properties in another object array 如何将数组值分配给其他对象的对象键? - How can I assign array values into object keys for other object? 使用 JavaScript 从对象中递归删除属性和值的最快方法是什么? - Using JavaScript what's the quickest way to recursively remove properties and values from an object? Javascript-替换文本中基于对象的值的最快,最有效的方法 - Javascript - The quickest and most efficient way to replace object-based values in text
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM