[英]how to insert object into beginning of object list, when it has unshift is not a function error?
How to insert object element in object which is list of object ? 如何在对象列表中的对象中插入对象元素?
I have this tiny piece of code in ReactJS: 我在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) 其中:(Chrome控制台输出)
> 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
? 如何将
data
插入allMessages
开头?
I have seen this reply How can I add new array elements at the beginning of an array in JavaScript? 我已经看到了此回复如何在JavaScript中的数组开头添加新的数组元素? and it is another case because my
allMessages
variable is an object
not an Array. 这是另一种情况,因为我的
allMessages
变量是一个object
而不是数组。
I got unshift is not a function
when i try to use unshift
当我尝试使用
unshift
时,我得到unshift is not a function
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;
Try 尝试
var arr = Array.prototype.slice.call(allMessages);
arr.unshift(data);
You can see how does Array.prototype.slice.call() work? 您可以看到Array.prototype.slice.call()如何工作?
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. 因此,基本上改变顺序将其放在最后,然后再次改变顺序,这很丑,但我知道它确实有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.