0

I have a nested JSON structure which will always have two keys by the name top_nest and mid_nest. However, at what level these two keys will be nested that may vary depending on the data set.

Each of top_nest and mid_nest has a 'remark' which is always null initially. I want to populate that remark key with the value from an array.

Below is my code which I tried only for mid_nest key :

var nestedjson = {
  edition: '1.3.0',
  OUTER_MOST: {
    secondnest: {
      mainstruct: {
        top_nest: [
          {
            portblair: 'mtlb_wc_way0_fcl',
            dir: 'left',
            locs: ['/loc/local'],
            remark: 'crc',
            id: 1544593588899,
            $count: 0,
            $parent: 0,
            $level: 1,
            $height: 256,
          },
        ],

        mid_nest: [
          {
            ept: 'qop[3:0:0]',
            remark: null,
            race: 'false',
            spt: ['mki[2:7:21]', 'epk[20:14.2:9.8]'],
            inod: 'u_pqp',
            mlace: 'pqp',
            portblair: ['qq[31:9:24]', 'ax[2:16:1]'],
            marcus: [
              {
                dir: 'left',
                h_loc: ['/op/locs'],
                sign: '0',
                portblair_w: '81',
                race_duty: '0',
              },
              {
                race_duty: '0',
                portblair_h: '28',
                sign: '2',
                dir: 'rigt',
                h_loc: ['/pr/op'],
              },
            ],
          },
          {
            eptt: 'yie[3:0:0]',
            remark: null,
            race: 'false',
            spt: ['mki[2:7:21]', 'epk[20:14.2:9.8]'],
            inod: 'u_pqp',
            mlace: 'pqp',
            portblair: ['qq[31:9:24]', 'ax[2:16:1]'],
            marcus: [
              {
                dir: 'left',
                h_loc: ['/op/locs'],
                sign: '0',
                portblair_width: '8',
                race_duty: '0',
              },
              {
                race_duty: '0',
                portblair_width: '8',
                sign: '2',
                dir: 'rigt',
                h_loc: ['/pr/op'],
              },
            ],
          },
        ],
      },
      qq: 'ss',
    },
  },
  dst: 'dss',
};

// function to take out the mid_nest structure to change its remark key
function findJson(json) {
  var mid_ret = [];
  for (var k in json) {
    if (k === 'mid_nest') {
      //console.log("breaking as mid reached");
      mid_ret = json[k];
      break;
    } else if (typeof json[k] === 'object') {
      findJson(json[k]);
    }
  }

  console.log('--after break--');
  return mid_ret;
}

var mid_ret = findJson(nestedJson);
var remark_arr = ['remark_1', 'remark2']; // array for assigning remarks

for (var i in remark_arr) {
  var rem = remark_arr;
  mid_ret[i]['remark'] = rem;
}

// assigning the changed mid_ret back to the original nestedJson
for (var k in nestedJson) {
  if (k === 'mid_nest') {
    nestedJson[k] = mid_ret;
  } else if (typeof nestedJson[k] === 'object') {
    continue;
  }
}

However, the above code is not working as in the findJson() ,

(i) even after matching the mid_nest the loop is not breaking, still iterating hence not returning the correct mid_nest value.

(ii) Because of that the rest of the processing like , changing the remark key by the array values and assigning it back to the original structure is not working.

Any help will be much appreciated.

Thanks.

3
  • 1
    Please learn the difference between JSON and Object Literal Notation. Commented Dec 12, 2018 at 8:06
  • 1
    You may not find top and mid nest because nestedjson does not contain such keys. Commented Dec 12, 2018 at 8:21
  • @HMR Apologies, I corrected my JSON, could you pls tell me what's going wrong? Commented Dec 12, 2018 at 9:13

1 Answer 1

1

Your function seems overly complex to me, although you will need to re-curse through your JSON. Take a look at this working example. This should simply set the remark value for mid_nest to mid_nest_remark and the remark value for top_nest to tpo_nest_remark. I'll let you tweak it yourself.

var nestedjson = {
  edition: '1.3.0',
  OUTER_MOST: {
    secondnest: {
      mainstruct: {
        top_nest: [
          {
            portblair: 'mtlb_wc_way0_fcl',
            dir: 'left',
            locs: ['/loc/local'],
            remark: 'crc',
            id: 1544593588899,
            $count: 0,
            $parent: 0,
            $level: 1,
            $height: 256,
          },
        ],

        mid_nest: [
          {
            ept: 'qop[3:0:0]',
            remark: null,
            race: 'false',
            spt: ['mki[2:7:21]', 'epk[20:14.2:9.8]'],
            inod: 'u_pqp',
            mlace: 'pqp',
            portblair: ['qq[31:9:24]', 'ax[2:16:1]'],
            marcus: [
              {
                dir: 'left',
                h_loc: ['/op/locs'],
                sign: '0',
                portblair_w: '81',
                race_duty: '0',
              },
              {
                race_duty: '0',
                portblair_h: '28',
                sign: '2',
                dir: 'rigt',
                h_loc: ['/pr/op'],
              },
            ],
          },
          {
            eptt: 'yie[3:0:0]',
            remark: null,
            race: 'false',
            spt: ['mki[2:7:21]', 'epk[20:14.2:9.8]'],
            inod: 'u_pqp',
            mlace: 'pqp',
            portblair: ['qq[31:9:24]', 'ax[2:16:1]'],
            marcus: [
              {
                dir: 'left',
                h_loc: ['/op/locs'],
                sign: '0',
                portblair_width: '8',
                race_duty: '0',
              },
              {
                race_duty: '0',
                portblair_width: '8',
                sign: '2',
                dir: 'rigt',
                h_loc: ['/pr/op'],
              },
            ],
          },
        ],
      },
      qq: 'ss',
    },
  },
  dst: 'dss',
};

var remark_arr = ['remark_1', 'remark2'];

$( document ).ready(function() {
    var val = assignRemarks( nestedjson );
    console.log(val)
});

function assignRemarks(theObject) {
    var result = null;
    if(theObject instanceof Array) {
        for(var i = 0; i < theObject.length; i++) {
            result = assignRemarks(theObject[i]);
            if (result) {
                break;
            }   
        }
    }
    else
    {
        for(var prop in theObject) {
            if(prop == 'top_nest') {
              //set the remark property for top-nest here
              theObject[prop].forEach(x => x.remark = 'top_nest_remark')
            }
            if(prop == 'mid_nest') {
              for (let i = 0; i < theObject['mid_nest'].length; i++)
              {
                //set the remark property for mid-nest here
                theObject['mid_nest'][i].remark = remark_arr[i];
              }
            }
            if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
                result = assignRemarks(theObject[prop]);
            } 
        }
    }
    return theObject;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

you are assigning mid_nest_remarks to all the remark field under mid_nest whereas they should be populated one by one from an array, Thanks
See the updated code which now gets the values from the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.