将对象属性值复制到另一个具有较少属性的对象

时间:2020-02-28 15:38:52

标签: javascript javascript-objects

考虑我有对象A:

const ObjectA = {
    attribute1: "text",
    attribute2: "text",
}

和对象B

const ObjectB = {
    attribute1: "tex2t",
    attribute2: "text2",
    attribute3: "text2"
}

是否可以为ObjectA属性赋予对象B的所有值?

我明白这句话:

ObjectA = ObjectB

会让ObjectA处理额外的attribute3,但这对我来说是不可取的。

如何将ObjectB的现有属性分配给ObjectA的属性,但不添加ObjectA不具有的属性,即attribute3。是否可以不执行循环操作?

谢谢

1 个答案:

答案 0 :(得分:0)

您将需要使用循环。这是一个.forEach()的示例,尽管还有其他多种有效方法。

const objectA = {
    attribute1: "text",
    attribute2: "text",
};
const objectB = {
    attribute1: "tex2t",
    attribute2: "text2",
    attribute3: "text2"
};

Object.keys(objectB).forEach(key => {
  if(objectA.hasOwnProperty(key)) objectA[key] = objectB[key];
});

console.log(objectA);