简体   繁体   English

JavaScript / TypeScript-对象仅分配可用属性

[英]JavaScript/TypeScript - Object assign only available properties

Following usecase: Lets assume I have an object with following properties: 以下用例:假设我有一个具有以下属性的对象:

const objOne = {
  car: 'ford',
  location: 'Munich',
  driver: 'John'
}

and a second Obj that only has some of the first Obj's properties: 第二个Obj仅具有第一个Obj的某些属性:

const objTwo = {
  car: 'BMW',
  driver: 'Marta'
}

Is there a way to assign the properties from the second obj to the first obj without loosing the properties from the first obj. 有没有一种方法可以第二个obj的属性分配给第一个obj,而不会丢失第一个obj的属性。 In this case location: 'Munich' . 在这种情况下, location: 'Munich' I know for a fact there is a method like Object.assign but this method completely copies the targeted obj, which I obviously don't want to. 我知道事实上有一个类似Object.assign但是该方法完全复制了目标obj,我显然不想这么做。

This is exactly the behaviour of Object.assign 这正是Object.assign的行为

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. Object.assign()方法用于将所有可枚举的自身属性的值从一个或多个源对象复制到目标对象。 It will return the target object. 它将返回目标对象。

 const objOne = { car: 'ford', location: 'Munich', driver: 'John' } const objTwo = { car: 'BMW', driver: 'Marta' } console.log(objOne); console.log(objTwo); Object.assign(objOne, objTwo); console.log('--assign--'); console.log(objOne); 

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

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