Reputation: 1004
I am trying to convert string to the JS Object. It is successfully using the JSON.parse method, but the problem is, when we delete some thing from the object it is missing/not deleting the ",". Check this program and output:
var jsonString = '[{"connectionName" : "conn1", "ipaddress" : "127.0.0.1","port" : "80"}, {"connectionName" : "conn2", "ipaddress" : "127.0.0.100","port" : "760"}]';
var a = JSON.parse(jsonString); // Successfully converted to Object and i can access them
delete a[1]; //deletes the conn2
var obj = {"connectionName" : "conn3", "ipaddress" : "127.0.0.100","port" : "760"};
a.push(obj);
console.dir(a);
Output:
[ { connectionName: 'conn1', ipaddress: '127.0.0.1', port: '80' },
,
{ connectionName: 'conn3',
ipaddress: '127.0.0.100',
port: '760' } ]
Can you observe that extra "," in between two objects:
'80' },
,
{ connectionName:
Upvotes: 3
Views: 304
Reputation: 1128
Use Array.prototype.splice(<index>, <numElements>, <newElements>)
to replace a element in the array.
var jsonString = '[{"connectionName" : "conn1", "ipaddress" : "127.0.0.1","port" : "80"}, {"connectionName" : "conn2", "ipaddress" : "127.0.0.100","port" : "760"}]';
var obj = {"connectionName" : "conn3", "ipaddress" : "127.0.0.100","port" : "760"};
var a = JSON.parse(jsonString);
a.splice(1, 1, obj); // remove starting at index 1, 1 element, and insert obj
console.dir(a);
Notice how the original array a
is modified without having to create a new variable. I used to use pop
and push
but found that splice
is cleaner when you have multiple elements to insert/remove from the array.
var jsonString = '[{"connectionName" : "conn1", "ipaddress" : "127.0.0.1","port" : "80"}, {"connectionName" : "conn2", "ipaddress" : "127.0.0.100","port" : "760"}]';
var obj1 = {"connectionName" : "conn3", "ipaddress" : "127.0.0.100","port" : "760"};
var obj2 = {"connectionName" : "conn4", "ipaddress" : "127.0.0.100","port" : "760"};
var obj3 = {"connectionName" : "conn5", "ipaddress" : "127.0.0.100","port" : "760"};
var a = JSON.parse(jsonString);
a.splice(1, 1, obj1, obj2, obj3); // remove starting at index 1, 1 element, and insert obj1, obj2, obj3
console.dir(a);
Upvotes: 1
Reputation: 45106
If you want to remove array item use splice
instead of delete
a.splice(1, 1);
And just to be clear. splice
will mutate the original array.
Upvotes: 3