2

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

Community
  • 1
  • 1
Ilja
  • 1,205
  • 1
  • 16
  • 33

3 Answers3

2

Try

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

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

Community
  • 1
  • 1
Ali Seyedi
  • 1,758
  • 1
  • 19
  • 24
1

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;
Lunny
  • 852
  • 1
  • 10
  • 23
0

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.

pompalini
  • 1,096
  • 7
  • 7