JavaScript - How to merge/append to an Object/Array - ReactJS - Spread Syntax

javascript merge array of objects by key
javascript spread object
spread object into array
javascript merge two arrays without duplicates
javascript merge objects with same key
merge two arrays with same keys javascript
es6 merge array of objects
javascript rest operator

I am having trouble trying to append something my object, using the spread syntax.

Depending on the fact whether the NewPerson is there for a private/professional occasion I want to append additional key/values to the object/array.

Somehow it does not work. Hopefully someone can help me out. :(

var NewPerson = [
    Firstname: this.state.addPersonFirstname,
    Lastname: this.state.addPersonLastname,
    Birthday: this.state.addPersonBirthday,
    Occasion: this.state.addPersonOccasion,
];


if (this.state.addPersonOccasion === 'OccasionProfessional') {
    NewPerson = [
        ...NewPerson,
        ...[ProfEmployerName: this.state.addPersonOccasionProfEmployerName],
        ...[ProfEmployerPLZ: this.state.addPersonOccasionProfEmployerPLZ],
        ...[ProfEmployerCity: this.state.addPersonOccasionProfEmployerCity],
        ...[ProfEmployerUVT: this.state.addPersonOccasionProfEmployerUVT]
    ]
}


if (this.state.addPersonOccasion === 'OccasionPrivate') {
    NewPerson = [
        ...NewPerson,
        ...[PrivPersonStreet: this.state.addPersonOccasionPrivPersonStreet],
        ...[PrivPersonPLZ: this.state.addPersonOccasionPrivPersonPLZ],
        ...[PrivPersonCity: this.state.addPersonOccasionPrivPersonCity]
    ]
}


var CombinedPersons


if (PreviousPersons === null) {
    CombinedPersons = NewPerson
} else {
    CombinedPersons = [...PreviousPersons, ...NewPerson]
}

You seem to be mixing up arrays and objects in this case. You want all the properties of a person isolated to a single entity. Object works out best in such cases.

var NewPerson = {
  Firstname: this.state.addPersonFirstname,
  Lastname: this.state.addPersonLastname,
  Birthday: this.state.addPersonBirthday,
  Occasion: this.state.addPersonOccasion,
};


if (this.state.addPersonOccasion === 'OccasionProfessional') {
  NewPerson = {
    ...NewPerson,
    ProfEmployerName: this.state.addPersonOccasionProfEmployerName,
    ProfEmployerPLZ: this.state.addPersonOccasionProfEmployerPLZ,
    ProfEmployerCity: this.state.addPersonOccasionProfEmployerCity,
    ProfEmployerUVT: this.state.addPersonOccasionProfEmployerUVT
  }
}


if (this.state.addPersonOccasion === 'OccasionPrivate') {
  NewPerson = {
    ...NewPerson,
    PrivPersonStreet: this.state.addPersonOccasionPrivPersonStreet,
    PrivPersonPLZ: this.state.addPersonOccasionPrivPersonPLZ,
    PrivPersonCity: this.state.addPersonOccasionPrivPersonCity
  ]
}


var CombinedPersons


if (PreviousPersons === null) {
  CombinedPersons = [NewPerson]
} else {
  CombinedPersons = [...PreviousPersons, {...NewPerson}]
}

Merge Arrays in one with ES6 Array spread · GitHub, Note: spread syntax doesn't work with multi-dimensional arrays see: https://​developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/​Spread_operator#Copy_an_array When you want to merge Objects in Array, then [{a: 1, b:  The spread operator is a useful and quick syntax for adding items to arrays, combining arrays or objects, and spreading an array out into a function’s arguments. Dr. Derek Austin 🥳 Follow

You should use Objects instead Array because Objects have key-value pairs. You could do (in ES6 syntax):

const { addPersonOccasion } = this.state;

const isProfessional = addPersonOccasion === 'OccasionProfessional';
const isPrivate = addPersonOccasion === 'OccasionPrivate';

const NewPerson = {
    Firstname: this.state.addPersonFirstname,
    Lastname: this.state.addPersonLastname,
    Birthday: this.state.addPersonBirthday,
    Occasion: this.state.addPersonOccasion,
    ...(isProfessional && {
      ProfEmployerName: this.state.addPersonOccasionProfEmployerName,
      ProfEmployerPLZ: this.state.addPersonOccasionProfEmployerPLZ,
      ProfEmployerCity: this.state.addPersonOccasionProfEmployerCity,
      ProfEmployerUVT: this.state.addPersonOccasionProfEmployerUVT
    }),
    ...(isPrivate && {
        PrivPersonStreet: this.state.addPersonOccasionPrivPersonStreet,
        PrivPersonPLZ: this.state.addPersonOccasionPrivPersonPLZ,
        PrivPersonCity: this.state.addPersonOccasionPrivPersonCity
    })
};


let CombinedPersons = [NewPerson];


if (PreviousPersons !== null) {
  CombinedPersons = [...PreviousPersons, ...CombinedPersons]
} 

Merge Object Properties with the Spread Operator, The ES6 spread operator feature in JavaScript allows for merging multiple object is for working with arrays and other iterable objects. while I tinker with Babel and React: merging multiple objects' properties into one object! Note: This syntax is not yet support by all browsers but you can use Babel with  When using spread syntax for function calls, be aware of the possibility of exceeding the JavaScript engine's argument length limit. See apply() for more details. Rest syntax (parameters) Rest syntax looks exactly like spread syntax, but is used for destructuring arrays and objects. In a way, rest syntax is the opposite of spread syntax.

You don't need to spread the new properties...

You can:

if (this.state.addPersonOccasion === 'OccasionProfessional') {
    NewPerson = {
        ...NewPerson,
        ProfEmployerName: this.state.addPersonOccasionProfEmployerName,
        ProfEmployerPLZ: this.state.addPersonOccasionProfEmployerPLZ,
        //... and so on
    }
}

2 Ways to Merge Arrays in JavaScript, Alternative Concat Syntax; Difference between Spread vs Concat. Example: Dealing with an arbitrary argument. Merge Array with Push 🤔; Browser Support  The spread syntax can also be used to make a shallow copy of an array or an object as it works by creating copies of the top-level elements of an array or key-value pairs of an object, and then

A combination of all your answers made the final version:

    var NewPerson = {
      Firstname: this.state.addPersonFirstname,
      Lastname: this.state.addPersonLastname,
      Birthday: this.state.addPersonBirthday,
      SigImage: this.sigPad.getCanvas().toDataURL('image/png'),
      Occasion: this.state.addPersonOccasion,
    };

    if (this.state.addPersonOccasion === 'OccasionProfessional') {
      NewPerson = {
        ...NewPerson,
        ProfEmployerName: this.state.addPersonOccasionProfEmployerName,
        ProfEmployerPLZ: this.state.addPersonOccasionProfEmployerPLZ,
        ProfEmployerCity: this.state.addPersonOccasionProfEmployerCity,
        ProfEmployerUVT: this.state.addPersonOccasionProfEmployerUVT
      }
    }

    if (this.state.addPersonOccasion === 'OccasionPrivate') {
      NewPerson = {
        ...NewPerson,
        PrivPersonStreet: this.state.addPersonOccasionPrivPersonStreet,
        PrivPersonPLZ: this.state.addPersonOccasionPrivPersonPLZ,
        PrivPersonCity: this.state.addPersonOccasionPrivPersonCity
      }
    }
    // Save the user input to NewPerson var - End

      // Create combined var with PreviousPersons and NewPerson - Start
      var CombinedPersons
      if (PreviousPersons === null) {
        CombinedPersons = [NewPerson]
      } else {
        CombinedPersons = [ ...PreviousPersons, NewPerson ]
      }
      // Create combined var with PreviousPersons and NewPerson - End

Using Object Spread Operator, is to use the object spread syntax recently added to the JavaScript specification​. The object spread operator is conceptually similar to the ES6 array spread We can simplify the todoApp example above by using the object spread syntax: install @babel/plugin-proposal-object-rest-spread and add it individually to the  I love how easy merging objects is using the spread operator. You can use Object.assign to accomplish the same feat but the spread operator makes things a bit shorter if you don't mind a slightly less descriptive syntax!

Using the spread operator in React setState - Jason Arnold, I'm currently building an app using React.js and ran into an issue that had me stumped. The trick here though is that this particular piece of state is an array of objects. The spread operator can be used to take an existing array and add another But when working with updating arrays, combining arrays,  Both the spread operator () and Object.assign () method perform a shallow merge. It means that if an object has a property that references to another object, the property of the original object and result target object will reference the same object.

How to merge properties of two JavaScript objects dynamically , Javascript objects are key-value paired dictionaries. We can merge different objects into one using the spread (…) operator. Syntax: object1 = {object2, The object spread syntax copies from the source object own and enumerable properties. Same as returned by Object.keys() function. 2. Object spread properties. Object spread syntax within the object literal extracts from source objects own and enumerable properties, and copies them into the target object.

JavaScript, Syntax of Spread operator is same as Rest parameter but it works completely opposite of it. of two or more strings(String concat() ) or is used to merge two or more arrays. The Math object in javascript has different properties that we can make use of to How to conditionally add a member to an object using JavaScript ? Merge Arrays in one with ES6 Array spread. GitHub Gist: instantly share code, notes, and snippets.

Comments
  • In your very first lines you are mistaking array brackets [] with object braces {}. The code that follows it is completely off as well since you're struggling to understance the difference. Lemme rewrite that.
  • Minor suggestion in the last line of code: replace {...NewPerson} with just NewPerson if I understand the intention of OP correctly.
  • Sure, we could do that but just did not want to have the reference of the original object in the array.
  • in the if (PreviousPersons === null) { it should be CombinedPersons = [NewPerson] I guess?
  • @ducmai My bad. Thought I fixed that as well. Thanks !
  • This is a cleaner solution than the accepted answer IMHO.