admin管理员组文章数量:1405618
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
3 Answers
Reset to default 2Try
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.
本文标签:
版权声明:本文标题:javascript - how to insert object into beginning of object list, when it has unshift is not a function error? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744875969a2629916.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论