简体   繁体   中英

How to push into an array of object using the spread operator to a specific element

I have an array as such

const arr = [a={} , b={}]

Now I know the spread operator is not for mutation or pushing but it is very easy to do so with.

I want this button to add elements to a when it's pressed

 <Button
title= {this.props.title}
 onPress={ this.roomNumberPressed }
 />

so the end results be something like :

arr = [a={1,2,3} , b={3,4,5}]

I want this button to add elements to a when it's pressed

As you said in your question, spread notation isn't for adding to existing objects. Your options are:

  1. Use spread to create a new object and assign that new object to a :

     a = {...a, ...theNewPropertiesToAdd}; 
  2. Use Object.assign to add new properties to the existing a :

     Object.assign(a, theNewPropertiesToAdd); 

Note I've just used a above because your const arr = [a={}, b={}] is a syntax error, and I can't tell whether you mean const arr = [{}, {}] (in which case a above is arr[0] ), or const arr = {a: {}, b: {}} (in which case a above is arr.a [and arr isn't an array]).

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