替换对象中的值

时间:2019-04-29 07:49:13

标签: reactjs object foreach

我希望基于键替换数据中的一些值,我有以下对象:

vbLf

上述对象中还包含两个其他对象-vbCrLfconst data = { data: { config: { bioObject: { dataBioOne: 1, dataBioTwo: "B", dataBioThree: "A", dataBioFour: 2, dataBioFive: 2, dataBioSix: 3, dataBioSeven: 1 }, pinObject: { dataPinOne: 5, dataPinTwo: "B0", dataPinThree: "A0", dataPinFour: 6 }, appletRegister: [ { aid: "A", filterApplet: null, bioApplet: false, pinApplet: false, defaultApplet: true }, { aid: "A", filterApplet: null, bioApplet: false, pinApplet: false, defaultApplet: true }, ] }, initialization: { defaultPin: "1111" } } }; 属性。我希望遍历该对象,并将这两个键及其值替换为新元素。

我的功能如下:

bioObject

但据我所知,我仅替换键,而不替换其值。如果我更改值的键,则无法遍历键,因此将无法替换此特定数据。有谁知道如何在这两个地方替换数据?

2 个答案:

答案 0 :(得分:1)

有几种方法可以解决此问题。您将在下面找到一种方法。另一种是使用Object.assign()或ES6对象扩展语法。 ...object

const data = {
    config: {
      bioObject: {
        dataBioOne: 1,
        dataBioTwo: "B",
        dataBioThree: "A",
        dataBioFour: 2,
        dataBioFive: 2,
        dataBioSix: 3,
        dataBioSeven: 1
      },
      pinObject: {
        dataPinOne: 5,
        dataPinTwo: "B0",
        dataPinThree: "A0",
        dataPinFour: 6
      },
      appletRegister: [
        {
          aid: "A",
          filterApplet: null,
          bioApplet: false,
          pinApplet: false,
          defaultApplet: true
        },
        {
            aid: "A",
            filterApplet: null,
            bioApplet: false,
            pinApplet: false,
            defaultApplet: true
          },
      ]
    },
    initialization: {
      defaultPin: "1111"
    }
};

handleSChange = () => {
    let profile = data;

    let obj;
    obj = Object.keys(profile.config).forEach((el) => {
      if (el == "bioObject") {
        profile.config[el] = {
          /* Put the new properties here if you want overwrite the existing object */
          newProp: 'newProp'
        };
      }
      if (el == "pinObject") {
        profile.config[el] = {
          /* Put the new properties here if you want overwrite the existing object */
          newProp: 'newProp'
        };
      }
    })   
 }
 
 handleSChange();
 console.log(data);

答案 1 :(得分:0)

由于您似乎正在使用带有状态的React类组件,因此以下方法应该起作用:

this.setState({
    data: {
        config: {
            ...profile,
            bioObject: bio,
            pinObject: pin
        }
    }
});