Mustafa
Mustafa

Reputation: 177

Accessing Sub Array in JSON [JavaScript]

var categories = [{
    "categories": {
        "data": [{
            "parent_id": 109,
        },
        {
            "parent_id": 0,
        }]
    }
}];

Hello, I have the above JSON object I'm trying to access the parent_id in categories with the following:

categories.data[i].parent_id !== 0

This is using a for loop with i < categories.length. I've google around and im not finding a good answer to this, is there a cleaner way to access the parent_id in the JSON?

EDIT: I implemented the suggested solutions with this and it's working 100% with access to the JSON however the Map() is taking them as undefined. Heres what I did:

let byParentId = new Map();
    for (let item of sample) {
      for (let data of item.categories.data) {
        if (data.parent_id !== 0) {
          if (!byParentId.has(data.parent_id)) {
            byParentId.set(data.parent_id, item.categories.data);
          } else {
            byParentId.get(data.parent_id).push(item.categories.data);
          }
        }
      }
    }

Upvotes: 0

Views: 578

Answers (4)

A.T.
A.T.

Reputation: 26312

I believe this is a clean and elegant way to work with arrays.

*

array.filter(i => i['categories']).map(i => i['categories'].data[0]).filter(d => d['parent_id'] !== 0).map(m => m.parent_id);

array .filter(i => i['categories']) // filter categories

.map(i => i['categories'].data[0]) // get first data

.filter(d => d['parent_id'] !== 0) // filter out parent_id with 0

.map(m => m.parent_id); // get desired parent_id

    
var array = [{
    "categories": {
        "data": [{
            "parent_id": 109,
        },
        {
            "parent_id": 0,
        }]
    }
}];

console.log(array.filter(i => i['categories']).map(i => i['categories'].data[0]).filter(d => d['parent_id'] !== 0).map(m => m.parent_id))

Upvotes: 0

sonEtLumiere
sonEtLumiere

Reputation: 4562

Try this:

for(let item of categories){
    for(let data of item.categories.data){
        console.log(data.parent_id)
    }
}

Upvotes: 1

Duy Tran
Duy Tran

Reputation: 110

your categories variable is array so you must start with categories[i].categories.data[i].parent_id

Upvotes: 0

RedGuy11
RedGuy11

Reputation: 381

categories is

{
success: true,
categories: {
data: [stuff]
}
}

So categories.data does not exist. So, instead, try categories.categories.data, then maybe rewrite your JSON structure.

Upvotes: 0

Related Questions