Cannot insert object into json object array

Excuse me for this simple problem - but I seem to be missing something obvious. Any pointer would be a big help.

I have JSON like

var whatever = [{ "key1" : { "text" : "text1","group" : "1" }, "key2" : { "text" : "text2","group" : "2" }, "key3" : { "text" : "text3","group" : "3" } }]; 

I'm trying to add another object (preferably at the beginning), but just couldn't get it to work.

 var str = '{"text":"text0","group":"0"}'; var obj = JSON.parse(str); whatever[0].put("key0",obj); 

Getting the error below:

Uncaught TypeError: whatever[0].put is not a function

fiddle

+5
source share
2 answers

There is no put function on the object. Use a property instead. If you want to assign a property that does not exist, it creates a new one and assigns a value to it.

 whatever[0]["key0"] = obj; 

What is associated with the beginning is preferably no order for the properties of the object. This is a false statement. If you want the ordering to try to think from the representation of an array of objects, and not from an array of an object containing objects.

Code examples

 const whatever = [{ "key1" : { "text" : "text1","group" : "1" }, "key2" : { "text" : "text2","group" : "2" }, "key3" : { "text" : "text3","group" : "3" } }]; const str = '{ "text" : "text0", "group" : "0" }'; const obj = JSON.parse(str); whatever[0]["key0"] = obj; console.log(whatever); 

Or use Object Assignment #

 const whatever = [{ "key1" : { "text" : "text1","group" : "1" }, "key2" : { "text" : "text2","group" : "2" }, "key3" : { "text" : "text3","group" : "3" } }]; const str = '{ "text" : "text0", "group" : "0" }'; const obj = JSON.parse(str); Object.assign(whatever[0], { key0: obj }) // this will also change the object console.log(whatever); 

My suggestion is to use an array of objects if you want something with order.

 const whatever = [ { "text" : "text1","group" : "1" }, { "text" : "text2","group" : "2" }, { "text" : "text3","group" : "3" } ]; const str = '{ "text" : "text0", "group" : "0" }'; const obj = JSON.parse(str); // Add to the start whatever.unshift(obj); console.log(whatever); // Add to the end whatever.push(obj); console.log(whatever); 
+3
source

maybe you want something like this

 var whatever = [{ "key1" : { "text" : "text1","group" : "1" }, "key2" : { "text" : "text2","group" : "2" }, "key3" : { "text" : "text3","group" : "3" } }]; Object.assign(whatever[0], {key4 : { "text" : "text4","group" : "4" }}); console.log(whatever); 
+1
source

Source: https://habr.com/ru/post/1272032/


All Articles