最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to push into an array of object using the spread operator to a specific element - Stack Overflow

programmeradmin3浏览0评论

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 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}]
Share Improve this question asked Sep 17, 2018 at 8:21 HypothesisHypothesis 1,3894 gold badges23 silver badges53 bronze badges 3
  • 2 Note: ... isn't, and can't be, an operator, neither when used for spread nor rest. It does things operators cannot do. Details. – T.J. Crowder Commented Sep 17, 2018 at 8:22
  • 2 const arr = [a={} , b={}] isn't valid syntax. Do you have an array, or an object with a and b properties? – T.J. Crowder Commented Sep 17, 2018 at 8:24
  • 2 Perhaps you mean {a: [], b: []}? – OliverRadini Commented Sep 17, 2018 at 8:26
Add a comment  | 

1 Answer 1

Reset to default 17

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]).

发布评论

评论列表(0)

  1. 暂无评论