javascript - how to insert object into beginning of object list, when it has unshift is not a function error? - Stack Overflow

How to insert object element in object which is list of object ?I have this tiny piece of code in React

How to insert object element in object which is list of object ?

I have this tiny piece of code in ReactJS:

var allMessages = this.state.data;
var newMessages = allMessages.unshift([data]); // i suppose it should be unshift if it was an array, but it is an object o_O
this.setState({ data: newMessages });

Where: (chrome console output)

> data
Object {id: "12", text: "1234124", date: "2016-04-28 20:00:07", sender: "user", type: "receiver"}
> allMessages
[Array[1], Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
> typeof allMessages
"object"

How to insert data into beginning of allMessages ?

I have seen this reply How can I add new array elements at the beginning of an array in JavaScript? and it is another case because my allMessages variable is an object not an Array.

I got unshift is not a function when i try to use unshift

How to insert object element in object which is list of object ?

I have this tiny piece of code in ReactJS:

var allMessages = this.state.data;
var newMessages = allMessages.unshift([data]); // i suppose it should be unshift if it was an array, but it is an object o_O
this.setState({ data: newMessages });

Where: (chrome console output)

> data
Object {id: "12", text: "1234124", date: "2016-04-28 20:00:07", sender: "user", type: "receiver"}
> allMessages
[Array[1], Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
> typeof allMessages
"object"

How to insert data into beginning of allMessages ?

I have seen this reply How can I add new array elements at the beginning of an array in JavaScript? and it is another case because my allMessages variable is an object not an Array.

I got unshift is not a function when i try to use unshift

Share Improve this question edited May 23, 2017 at 10:33 CommunityBot 11 silver badge asked Apr 28, 2016 at 17:10 IljaIlja 1,2251 gold badge16 silver badges33 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 2

Try

var arr = Array.prototype.slice.call(allMessages);
arr.unshift(data);

You can see how does Array.prototype.slice.call() work?

I can think of this work around;

var tempMessage= {};
tempMessage.data = data;
for(var key in allMessages){
     tempMessage[key] = allMessages[key];
}

Than just set it back

allMessages = tempMessage;

Hacky business but for me the following did it:

this.setState({data: this.state.data.reverse().concat(data).reverse()});

So basically change the order put it in last and change the order again, ugly I know but it does work.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744875969a4598548.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信