unwanted keys in JSON object - javascript

hi i am creating a JSON object after executing a loop. the problem is the JSON object have additional keys. i don't want that keys. that keys are generated by me. for arraigning the json according my requirement. this is code i am using for create my JSON object
var bankdata = data;
var updatebankdata = {}
for (var key in bankdata) {
var id = +key.substr(key.length - 1);
if (isNaN(id)) {
updatebankdata[0] = updatebankdata[0] || {};
updatebankdata[0][key] = bankdata[key];
} else {
var uniqid=$("#bankaccount"+id).attr("uniq_id");
updatebankdata[id] = updatebankdata[id] || {};
var field = key.substring(0, key.length - 1);
updatebankdata[id][field] = bankdata[key];
updatebankdata[id]["uniquid"] = uniquid;
}
}
return updatebankdata;
}
my bank data is like
{bankname1: "new", micrcode1: "mkkk", comments1: "commentsfvfdv", bankname2: "bankfgname", micrcode2: "micrfgcode"…}
i want to change it into like this way
[{bankname1: "new", micrcode1: "mkkk", comments1:
"commentsfvfdv"},{bankname2: "bankfgname", micrcode2: "micrfgcode"}]
but still it getting like this .its not good
{"0":{bankname1: "new", micrcode1: "mkkk", comments1:
"commentsfvfdv"},"1":{bankname2: "bankfgname", micrcode2: "micrfgcode"}
what is the mistake in my code?

You need to use an array instead of an object. Like so:
function func(data) {
var bankdata = data;
var updatebankdata = []; // ARRAY instead of Object
for (var key in bankdata) {
var id = +key.substr(key.length - 1);
if (isNaN(id)) {
updatebankdata[0] = updatebankdata[0] || {};
updatebankdata[0][key] = bankdata[key];
} else {
var uniqid=$("#bankaccount"+id).attr("uniq_id");
updatebankdata[id] = updatebankdata[id] || {};
var field = key.substring(0, key.length - 1);
updatebankdata[id][field] = bankdata[key];
updatebankdata[id]["uniquid"] = uniqid; // CHANGED to "uniqid" to match variable declaration above, not the key on the left is still "uniquid"
}
}
return updatebankdata;
}
Then you can get result like:
JSON.stringify(func({name: 'someval', val: 123}));
"[{"name":"someval","val":123}]"

assign
var updatebankdata = [];
then push your object to array like this
updatebankdata.push(yourObject)

Related

How to generate array key using array index in for on the associative array in javascript

Is it possible to generate array keys using the array index in the "for" to create associative arrays?
I want the values in the index array in the "for" to be used as keys in the associative array
The sample code that you want to get the value for making an associative array is in the middle of the *** sign :
if(data.status == 422){
let msg = data.responseJSON.errors;
let msgObject = Object.keys(msg);
for (let i = 0; i < msgObject.length; i++) {
if (msg[msgObject[i]]) {
let msgObjectIndex = msgObject[i];
let columnIndex = {
||
\/
***msgObject[i]*** : column[msgObject[i]]
/\
||
};
console.log(columnIndex);
}
}
}else {
alert('Please Reload to read Ajax');
console.log("ERROR : ", e);
}
},
then variable column is:
let column = {
'nama_paket' : $('.edit_error_nama_paket'),
'tipe_berat' : $('.edit_error_tipe_berat'),
'harga' : $('.edit_error_harga'),
'id_service' : $('.edit_error_id_service'),
};
I tried the code above to get the following error: Uncaught SyntaxError: Unexpected token '['
thanks
You can generate computed property names with [] syntax
Simple example:
let obj = {};
['a','b','c'].forEach((e,i) => {
let computed = {[e]:i};
Object.assign(obj, computed)
})
console.log(obj)
Here couple of ways you can do, see my comments.
one way is as suggested by #charlietlf.
After object creation, add the key/value
let msg = data.responseJSON.errors;
let msgObject = Object.keys(msg);
for (let i = 0; i < msgObject.length; i++) {
if (msg[msgObject[i]]) {
let msgObjectIndex = msgObject[i];
const newKey1 = `MyNewKey${2 + 3}`; // sample
let columnIndex = {
// One way is
[newKey1]: column[msgObject[i]],
};
// Alternatively, we can add the generated key and value to obj
const newKey2 = msgObject[i];
// or something like newKey2 = `MyKey${msgObject[i]}`
columnIndex[newKey2] = column[msgObject[i]];
console.log(columnIndex);
}
}

Convert Array to JSON Array

How do I convert
["ID:2","ID:3","ID:4"]
to
[{
"ID":2
},
{
"ID":3
},
{
"ID":4
}]
because this type of data i have to send to my webservice
For getting an array with objects, you could split the strings and build a new object with the wanted property and the numerical value.
var data = ["ID:2","ID:3","ID:4"],
result = data.map(function (s) {
var p = s.split(':'),
t = {};
t[p[0]] = +p[1];
return t;
});
console.log(result);
var newArrayOfObjs =arr.map((item)=> {
var obj = {};
var splitItems = item.split(':');
obj[splitItems[0]] = splitItems[1];
return obj;
}
You'll have to split the string on ':' and set the 0th element as key and 1st element as value.
var aryExample = ["ID:2","ID:3","ID:4"], aryNew = [];
for( var i in aryExample ) {
aryNew.push({ID:Number(aryExample[i].split(":")[1])});
}
console.dir(aryNew);
That should do it.

Removing "object having an array field" from an array in javascript

Here is my code:
var subMed = [ {med:'bm', sub:[ 'a' , 'b' ]} , {med:'bm', sub:[ 'c' , 'd' , 'e' ]} ];
var sal = [ {num:"1",amount:"500"} ];
var t = {Class:"1", subMeds:subMed, numOfSub:2, sals:sal };
var infoAcademic = [];
infoAcademic.push(t);
subMed = [ {med:'em', sub:[ 'p']} , {med:'bm', sub:[ 'r' , 's' ]} ];
sal = [ {num:"2",amount:"1500"},{num:"1",amount:"700"} ];
t = {Class:"1", subMeds:subMed, numOfSub:1, sals:sal };
infoAcademic.push(t);
var tempObj = infoAcademic[1]; // an object
var mediumSubjects = tempObj["subMeds"]; // an array
console.log(mediumSubjects);
for(i=0;i<mediumSubjects.length;i++){
var temp = {}; // object
temp = mediumSubjects[i];
if(temp["med"] == 'bm'){
tempObj["numOfSub"] = tempObj["numOfSub"] - temp["sub"].length;
var salArr = tempObj["sals"]; // array
var j = salArr.length;
if(salArr.length > 0){
while(j--){
var salObj = salArr[j]; // object
var howManySub = salObj["num"];
if(howManySub > tempObj["numOfSub"]){
salArr.splice(j,1);
}
}
}
console.log("removing from the medSubjects list: ");
console.log(temp);
var removed = mediumSubjects.splice(i, 1);
break;
}
}
console.log("removed element: ");
console.log(removed);
console.log(mediumSubjects);
When I write this code this an online js editor https://js.do/ , the code gives result as per expected. But when I incorporate this code in a onclick function of my JSP page, no element gets removed from the mediumSubjects array. The removed element shows empty.
However, when I comment out this portion:
tempObj["numOfSubj"] = tempObj["numOfSub"] - temp["sub"].length;
var salArr = tempObj["sals"]; // array
var j = salArr.length;
if(salArr.length > 0){
while(j--){
var salObj = salArr[j]; // object
var howManySub = salObj["num"];
if(howManySub > tempObj["numOfSub"]){
salArr.splice(j,1);
}
}
}
the code surprisingly behaves as expected- it removes the element from the mediumSubjects array.
Is there any synchronization issue or something else? Why this sort of unusual behavior?
N.B. I need to remove elements from the array mediumSubjects, so delete won't work here.
Try this variant:
var newMedSub = medSub.filter(function(elem) {
return elem.med !== 'em';
});
It will help you to get a new array without unnessessary object.
All you actually need is to iterate over the outer array and in the body of this loop you need to iterate over the object keys.
for Example:
// removing med key from the array.
medSub.forEach(obj => {
for (let key in obj) {
if (key === 'med' && obj[key] === 'em') {
delete obj[key];
}
}
});
I hope this helps.

Issue with javascript array variables

I am using javascript in my app which is a rhino javascript engine. I like to use array for an array.
The following code is my actual working code.
while (input.hasNext()) {
var data = input.next();
var new_data = {};
var i = 0;
while(i<data.get('total_entries')){
new_data.entries = data.get('total_entries');
new_data.id = data.get('out').get(i).get('id');
output.write(new_data);
i++;
}
}
I need to create array for new_data[].
while (input.hasNext()) {
var data = input.next();
var new_data[] = {};
var i = 0;
while(i<data.get('total_entries')){
new_data[i].entries = data.get('total_entries');
new_data[i].id = data.get('out').get(i).get('id');
output.write(new_data[i]);
i++;
}
}
But its not working. So, help me to create array variable in it.
Thanks.
You mean something like this:
while (input.hasNext()) {
var data = input.next();
var new_data = [];
var i = 0;
while(i<data.get('total_entries')){
new_data.push({entries: data.get('total_entries'), id: data.get('out').get(i).get('id')});
output.write(new_data[i]);
i++;
}
}
var new_data[] = {};
First of all, that's invalid JavaScript.
new_data[i]
Looks like you want new_data to be an array of objects. Why not declare it as one and add objects on every iteration of the while loop:
var new_data = [];
while(...){
new_data.push({
entries: ...
id: ...
});
}

how to build javascript object dynamically with array values

I need to create the object property from array values and assign some values to that for example
var main_obj = {};
var dynamic_array = ["value1", "value2", "value3", "value4"];
From dynamic_array I need to create main_obj like:
main_obj[value1][value2][value3] = some_value;
Please give me some suggestions.
dynamic_array.forEach(function(prop){
main_obj[prop] = some_value;
});
this is another way
var dynamic_array = ["value1","value2","value3"];
var value = 'your value';
function createobj(dynamic_array,value){
var count = dynamic_array.length;
var text= '';
var ended = '';
for(var i = 0; i < count; i++){
text += '{"'+dynamic_array[i]+'":';
ended +='}';
}
text += '"'+value+'"'+ended;
return JSON.parse(text);
}
console.log(createobj(dynamic_array,value));
Trying to interpretate your question, this may be a solution to what you are looking for:
function createNestedProperties(obj, array, value) {
var result = {};
var result_tmp = obj;
var i = 0;
while (i < array.length) {
if (i < (array.length - 1))
result_tmp[array[i]] = {};
else
result_tmp[array[i]] = value;
result_tmp = result_tmp[array[i]];
i++;
}
return obj;
}
used this way:
var main_obj = {"value1":{"value2":{"value3":{}}}};
var dynamic_array = ["value1", "value2", "value3"];
main_obj = createNestedProperties(main_obj, dynamic_array, {"value_Z":"new value"});
Resulting object:
{"value1":{"value2":{"value3":{"value_Z":"new value"}}}}
This function would override existing properties in main_obj if already there.
i parse through the object recursively rather than building that jQuery - How to recursively loop over an object's nested properties?
function recursiveIteration(main_obj) {
for (var property in main_obj) {
if (property == value3)
{
main_obj[property] = {"value4":test};
}
else
{
recursiveIteration(main_obj[property]);
}
}
}
recursiveIteration(main_obj);

Categories

Resources