Convert JSON array into normal json in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented ProgrammingJSON

Suppose, we have a JSON array with key/value pair objects like this −

const arr = [{
   "key": "name",
   "value": "john"
},
{
   "key": "number",
   "value": "1234"
},
{
   "key": "price",
   "value": [{
      "item": [{
         "item": [{
            "key": "quantity",
            "value": "20"
         },
         {
            "key": "price",
            "value": "200"
         }]
      }]
   }]
}];

We are required to write a JavaScript function that takes in one such array.

The function should prepare a new array where data is simply listed against key value instead of this complex structure.

Therefore, for the above array, the output should look like this −

const output = {
   "name": "john",
   "number": "1234",
   "price": {
      "quantity": "20",
      "price": "200"
   }
};

Example

The code for this will be −

const arr = [{
   "key": "name",
   "value": "john"
},
{
   "key": "number",
   "value": "1234"
},
{
   "key": "price",
   "value": [{
      "item": [{
         "item": [{
            "key": "quantity",
            "value": "20"
         },
         {
            "key": "price",
            "value": "200"
         }]
      }]
   }]
}];
const simplify = (arr = []) => {
   const res = {};
   const recursiveEmbed = function(el){
      if ('item' in el) {
         el.item.forEach(recursiveEmbed, this);
         return;
      };
      if (Array.isArray(el.value)) {
         this[el.key] = {};
         el.value.forEach(recursiveEmbed, this[el.key]);
         return;
      };
      this[el.key] = el.value;
   };
   arr.forEach(recursiveEmbed, res);
   return res;
};
console.log(simplify(arr));

Output

And the output in the console will be −

{
   name: 'john',
   number: '1234',
   price: { quantity: '20', price: '200' }
}
raja
Published on 24-Nov-2020 10:16:00
Advertisements