Not able to insert object into array of json object

Viewed 220

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

I have a JSON like

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

I am trying to add another object(at start preferably) - 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 below error:

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

fiddle

2 Answers

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

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

What is related to at start preferably, there is no order for object properties. It is a wrong statement. If you want ordering try to think from the view of array of objects instead of array of object, which contains 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#assign

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);

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);

Related