Home > Software engineering >  JavaScript loop through multidimensional array of object
JavaScript loop through multidimensional array of object

Time:10-28

I have this variable:

let obj = {
    "aff_link": "https://event.2performant.com/events/click?ad_type=product_store&unique=83b281931&aff_code=d79aaed64&campaign_unique=2e49eab4f",
    "availability": true,
    "brand": "Casio",
    "date_add": 1666792631,
    "date_upd": 1666792631,
    "id": 78594,
    "price": 159.24,
    "product_type": "Ceasuri de mana",
    "title": "Ceas Casio CLASSIC LTP-1303L-7BVEF",
    "update_history": [
        {
            "id_feed": 108,
            "date_upd": 1666794541,
            "address" : [
                {
                    "present" :  "Dhanmondi 15",
                    "permanent" : "Gulshan 2"  
                }
            ]
        }
    ],
    "vgt_id": 0,
    "originalIndex": 0
};

Now, I have an array called:

let arr = [];

Now Using below function I loop through all the property and store it to variable arr.

function eachRecursive(obj) {
    for (var k in obj)  {
        if( k !== 'additional_image_link' ) {
            if (typeof obj[k] == "object" && obj[k] !== null) {
                eachRecursive(obj[k]);            
            } else {
                arr.push({
                    [k] : obj[k]
                })              
            }
        }
    }
}

Now, usinge console.log( arr ) I got this output:

[ { aff_link:
     'https://event.2performant.com/events/click?ad_type=product_store&unique=83b281931&aff_code=d79aaed64&campaign_unique=2e49eab4f' },
  { availability: true },
  { brand: 'Casio' },
  { date_add: 1666792631 },
  { date_upd: 1666792631 },
  { id: 78594 },
  { price: 159.24 },
  { product_type: 'Ceasuri de mana' },
  { title: 'Ceas Casio CLASSIC LTP-1303L-7BVEF' },
  { id_feed: 108 },
  { date_upd: 1666794541 },
  { present: 'Dhanmondi 15' },
  { permanent: 'Gulshan 2' },
  { vgt_id: 0 },
  { originalIndex: 0 } 
]

if you look at it you can see the there is no key called update_history, right ? I want that above output should contain update_history as a key and the value should contain id_feed, date_upd, present, permanent with their corresponding value.

Can you help me please?

CodePudding user response:

update_history is an object (arrays are objects too), so your code recurses through it (hence you have all the subkeys of update_history in your output). You can prevent that by checking that obj[k] is not an array before recursing:

let obj = {
    "aff_link": "https://event.2performant.com/events/click?ad_type=product_store&unique=83b281931&aff_code=d79aaed64&campaign_unique=2e49eab4f",
    "availability": true,
    "brand": "Casio",
    "date_add": 1666792631,
    "date_upd": 1666792631,
    "id": 78594,
    "price": 159.24,
    "product_type": "Ceasuri de mana",
    "title": "Ceas Casio CLASSIC LTP-1303L-7BVEF",
    "update_history": [
        {
            "id_feed": 108,
            "date_upd": 1666794541,
            "address" : [
                {
                    "present" :  "Dhanmondi 15",
                    "permanent" : "Gulshan 2"  
                }
            ]
        }
    ],
    "vgt_id": 0,
    "originalIndex": 0
};

let arr = [];

function eachRecursive(obj) {
    for (var k in obj)  {
        if( k !== 'additional_image_link' ) {
            if (typeof obj[k] == "object" && !Array.isArray(obj[k]) && obj[k] !== null) {
                eachRecursive(obj[k]);            
            } else {
                arr.push({
                    [k] : obj[k]
                })              
            }
        }
    }
}

eachRecursive(obj)

console.log(arr)

CodePudding user response:

why you need recursion? if you need only update_history, pick him obj['update_history']

CodePudding user response:

If all you want to do is create an html table with two columns (one for the obj keys and one for the obj values), here is a straightforward way to do it without needing recursion.

const obj = {
    "aff_link": "https://event.2performant.com/events/click?ad_type=product_store&unique=83b281931&aff_code=d79aaed64&campaign_unique=2e49eab4f",
    "availability": true,
    "brand": "Casio",
    "date_add": 1666792631,
    "date_upd": 1666792631,
    "id": 78594,
    "price": 159.24,
    "product_type": "Ceasuri de mana",
    "title": "Ceas Casio CLASSIC LTP-1303L-7BVEF",
    "update_history": [
        {
            "id_feed": 108,
            "date_upd": 1666794541,
            "address" : [
                {
                    "present" :  "Dhanmondi 15",
                    "permanent" : "Gulshan 2"  
                }
            ]
        }
    ],
    "vgt_id": 0,
    "originalIndex": 0
};

let html = '';
html  = '<table>';
for (let key in obj) {
  if (key === 'additional_image_link') continue;
  const val = obj[key];
  html  = '<tr>';
  html  =   `<td>${key}</td>`;
  html  =   `<td>${JSON.stringify(val)}</td>`;
  html  = '</tr>';
}
html  = '</table>';

const outputElem = document.querySelector('#output');
outputElem.innerHTML = html;
td {
  border: 1px solid black;
}
<div id="output"></div>

  • Related