0
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);
          }
        }
      }
    }
0

4 Answers 4

1

Try this:

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

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

1 Comment

Hey, I liked this solution and I implemented it however the data is undefined going into my Map. I edited the question with it
0

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.

1 Comment

pheew that was severely overlooked because I was handed the JSON structure this way. Thanks for pointing it out
0

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

Comments

0

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))

Comments

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.