我如何匹配所有值而不让 for-in 循环中的闭包覆盖对象?

How can I match all the values without having the closure in a for-in loop overwrite the object?

我正在尝试获取平面对象的值,并在键匹配时将它们复制到嵌套对象的值中。

this.flatProfile = {
    address1: "456 Grand Street"
    address2: "Apt 5i"
    city: "Brooklyn"
    email: "asdf@sdzf.com"
    mobile: "2163861880"
    phone: "2163861880"
    state: "NY"
    zip: "55111"
}

this.profileData = {
    physical_address: {
        address1: "",
        address2: "",
        city: "",
        zip: "",
        state: "",
    },
    mailing_address: {
        address1: "",
        address2: "",
        city: "",
        zip: "",
        state: "",
    },
    contact: {
        email: "",
        primary_phone_number: "",
        secondary_phone_number: ""
    }
}

我正在使用 for 循环检查键是否匹配,如果匹配,我将值设置为 this.profileData 中的相应键。

 // const arr = []; 
    for(var flatProfileKey in this.flatProfile) {
        for(var key in this.profileData['physical_address']) {

            if(flatProfileKey === key) {
                // arr.push({[key]: this.flatProfile[key]})

                this.profileData['physical_address'] = {
                    [key]: this.flatProfile[key]
                }
            }
        }

        for(var key in this.profileData['mailing_address']) {
            if(flatProfileKey === key) {
                // arr.push({[key]: this.flatProfile[key]})
                this.profileData['mailing_address'] = {
                    [key]: this.flatProfile[key]
                }
            }
        }

        for(var key in this.profileData['contact']) {
            if(flatProfileKey === key) {
                // arr.push({[key]: this.flatProfile[key]})
                this.profileData['contact'] = {
                    [key]: this.flatProfile[key]
                }

                console.log('profileData', this.profileData)
            }
        }
    }

我遇到的问题是因为 for-in 循环创建了一个闭包,只有最后一个值被匹配,所以 this.profileData returns

this.profileData = {
    contact: {
        email: "asdf@sdzf.com"
    },
    mailing_address: {
        state: "NY"
    },
    physical_address: {
        state: "NY"
    }
}

如何在不让闭包覆盖对象的情况下匹配所有值?我尝试在 for 循环之外创建一个数组并将值推送给它,但这没有用。这就是注释掉的 arr 的用途。此外,我需要 return 一个嵌套对象,因为这是我需要传递给我的组件的对象。

不要在每次找到匹配项时都创建新对象...只需将值分配给现有对象

示例更改:

if (flatProfileKey === key) {
  this.profileData['physical_address'] = {
    [key]: this.flatProfile[key]
  }
}

if (flatProfileKey === key) {
  this.profileData['physical_address'][key] = this.flatProfile[key]
}

您每次都在覆盖对象,而只是更新一个 属性:

this.profileData['physical_address'][key] = this.flatProfile[key]