0

What I want to do is create a multi-checkbox filter. So when I click the checkbox titled 'Accessories', it returns all items that contain the value 'Accessories' under the property 'type'. But before I do that I need to understand how to manipulate and traverse my data properly.

I have a json file named products that contains all of the products of a store and it looks like so.

[
  {
  "id" : 1,
  "name" : "Net and Post Set",
  "type" : "Accessories",
  "price" : 35,
  "desc" : "It's a solid blade. 11111"
},{
  "id" : 10,
  "name" : "Platinum 3* Balls (Bag of 36)",
  "type" : "Balls",
  "price" : 12,
  "desc" : "It's a solid blade. 11111"
},{
  "id" : 22,
  "name" : "Galaxy MC2",
  "type" : "Blades",
  "category" : "Composite",
  "price" : 60,
  "desc" : "It's a solid blade. 11111"
},
{
  "id" : 23,
  "name" : "Oversized Carbon fl, st",
  "type" : "Blades",
  "category" : "Composite",
  "price" : 32,
  "desc" : "It's a solid blade. 11111"
}
]

But when i print it out in the console it is a mess. Firstly, it prints as an array within an array. Secondly, that nested array has the key '0' and the rest of the values also have keys.

Lets assume im passing products.json to a function. In order to print the array without the leading zero to the console I have to call console.log(props.products[0]).

But my question is how do I reference the "type" property of all of the Objects in props.products[0]. props.products[0].type returns undefined. Which means I would have to step through each and every item?

1
  • Please do not downvote this question without explaining why. Commented Aug 10, 2020 at 0:32

1 Answer 1

1

You can use Array#map with destructuring.

const props = {
  products: [
    [{ "id": 1, "name": "Net and Post Set", "type": "Accessories", "price": 35, "desc": "It's a solid blade. 11111" }, { "id": 10, "name": "Platinum 3* Balls (Bag of 36)", "type": "Balls", "price": 12, "desc": "It's a solid blade. 11111" }, { "id": 22, "name": "Galaxy MC2", "type": "Blades", "category": "Composite", "price": 60, "desc": "It's a solid blade. 11111" }, { "id": 23, "name": "Oversized Carbon fl, st", "type": "Blades", "category": "Composite", "price": 32, "desc": "It's a solid blade. 11111" } ]
  ]
};
const types = props.products[0].map(({type})=>type);
console.log(types);

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

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.