简体   繁体   中英

react-native(mobX) : How to add a new object to existing object

I am trying to add a new object to existing object .

In my mobx Store I have an existing object which contains one user :

@observable user = {
    id: 101,
    email: 'kevin@dev.com',
    personalInfo: {
        name: 'kevin',
        address: {
            city: 'Costa Mesa',
            state: 'CA'
        }
    }
}

I want to add another user to existing object:

id: 102,
    email: 'john@dev.com',
    personalInfo: {
        name: 'john',
        address: {
            city: 'New York',
            state: 'NY'
        }

    }

I want my final code to look like this:

@observable user = {
    id: 101,
    email: 'kevin@dev.com',
    personalInfo: {
        name: 'kevin',
        address: {
            city: 'Costa Mesa',
            state: 'CA'
        }
    },
    id: 102,
    email: 'john@dev.com',
    personalInfo: {
        name: 'john',
        address: {
            city: 'New York',
            state: 'NY'
        }
    }
}

What would be the correct format to add another object to the existing object?

Would this work?

updateObjectState (){

const user2 = {
  id: 102,
  email: 'john@dev.com',
  personalInfo: {
      name: 'john',
      address: {
          city: 'New York',
          state: 'NY'
      }
  }
}
  store.pressedDate = [...store.pressedDate, user2] 
}

Thanks in advance!

Your desired result can't be achieved, as id is repeated so it will overwrite last id, wrap each user in object or use array

using id as key and placing values, when you want to add new user just create a new key value pair on user

@observable user = {
    '101':{
           id: 101,
           email: 'kevin@dev.com',
           personalInfo: {
           name: 'kevin',
           address: {
             city: 'Costa Mesa',
             state: 'CA'
           }
      }
   }
}

Or having user as an array, to add new user just push the value in user

@observable user = [{
    id: 101,
    email: 'kevin@dev.com',
    personalInfo: {
        name: 'kevin',
        address: {
            city: 'Costa Mesa',
            state: 'CA'
        }
    }
}]

PS - I am not sure how you're using data, but i will go with the object way,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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