How to push fields details into Object

Supriya25
Tera Guru

Hi All,

Kindly help to deal below situation.
now kindly help me how to deal below format if there is nested values and push into Object {}

 

 

 

var j={
         info:{
           data: [ 
             {
              rollNumber:"98087",
              name:"ABC",
              section:"A"
              }, {
              rollNumber:"98097",
              name:"ABCD",
              section:"B"
              }
            ]
        }
  }

 

 

 

Script:

system Property : List of student fields
values: rollNumber,name, section,

 

var gr = gs.getProperty("list of student fields").split(',');
var parse = JSON.parse(j);
var result = parse.info.data;
var obj={};
var final=[];
for(var i in gr){
if(gr[i] in result){
obj[gr[i]] = result[gr[i]].toString();
}
}
final.push(obj);

 

 

 

 

 

 

 

1 ACCEPTED SOLUTION

Can't reproduce, check your input data maybe. I've used your data as you've described and it works fine (eg: run this in a BG script):

 

var fields = "rollNumber, name, section".split(/,\s*/);
var j = { info:{ data: [ { rollNumber:"98087", name:"ABC", section:"A" }, { rollNumber:"98097", name:"ABCD", section:"B" } ] } };
var data = j.info.data;

var res = [];
data.forEach(function(obj) {
  var resObj = {};
  fields.forEach(function(field) {
    if (field in obj)
      resObj[field] = obj[field];
  });
  res.push(resObj);
});

gs.info(JSON.stringify(res, null, 2));
/* Output:
[
  {
    "rollNumber": "98087",
    "name": "ABC",
    "section": "A"
  },
  {
    "rollNumber": "98097",
    "name": "ABCD",
    "section": "B"
  }
]
*/

 

View solution in original post

11 REPLIES 11

Working..! Thank you so much

Could you please tell me what is wrong in my code, it giving below output
[{"rollNumber":98087,"name":"ABC","section":"A"},"rollNumber":98087,"name":"ABC","section":"A"}]

 

 

var arr=[];
var pr=gs.getProperty('ListOfStudentFields").split(',');
var gr3= JSON.stringify(j);
var aa = JSON.parse(gr3);
var result = aa.info.data;
var grObj={};
for( var i=0;i<result.length;i++){
for(var key in pr){
if(pr[key] in result[I]){
grObj[pr[key]]=result[I][pr[key]];
}
}
arr.push(grObj);
}
gs.info(JSON.stringify(arr));

 

 

 

The issue with your code is that you keep modifying the same grObj object reference on each iteration, so it changes the object that you've already pushed into your array. You could fix it by making sure you create a new unique object on each iteration by moving grObj down a line:

// var grObj={}; <-- remove this...
for(var i=0;i<result.length;i++){
  var grObj = {}; // <--- move to here

Fixing that should make your code work too (provided you use a lowercase I when indexing). But besides that, your variable names can be improved to be more meaningful. You also shouldn't be using a for...in loop to iterate array indexes, in your case though your code will work with it.