问题
In an application on react
I have this json data from var product
I am trying to store "category names" from below json
like
category: 'Jumpsuits,Cargo Jumpsuit' // this is the desired output
product = {
"isConfigurableProduct": true,
"id": "bdg-workwear-denim-boiler-suit",
"categories": [
{
"id": 2437,
"name": "Jumpsuits",
"url_key": "jumpsuits",
"level": 4,
"url_suffix": ".html",
"breadcrumbs": [
{
"category_id": 3,
"category_level": 2,
"category_name": "Clothing",
"category_url_key": "clothing",
"category_url_path": "clothing"
},
{
"category_id": 82,
"category_level": 3,
"category_name": "Jumpsuits & Rompers",
"category_url_key": "jumpsuits-rompers",
"category_url_path": "clothing/jumpsuits-rompers"
}
],
"path": "clothing/jumpsuits-rompers"
},
{
"id": 2492,
"name": "Cargo Jumpsuit",
"url_key": "cargo-jumpsuit",
"level": 5,
"breadcrumbs": [
{
"category_id": 3,
"category_name": "Clothing",,
"category_url_path": "clothing"
},
{
"category_id": 82,
"category_name": "Jumpsuits & Rompers",
"category_url_path": "clothing/jumpsuits-rompers"
},
{
"category_id": 2437,
"category_name": "Jumpsuits",
"category_url_key": "jumpsuits",
}
],
"path": "clothing/jumpsuits-rompers/jumpsuits"
}
]
}
Is their any way i can separate it from this json ? What would be the optimized way of fetching it ? Any thoughts , appriciated
回答1:
You can iterate and push category names to a separate array and separate them.-
const product = {
"isConfigurableProduct": true,
"id": "bdg-workwear-denim-boiler-suit",
"categories": [
{
"id": 2437,
"name": "Jumpsuits",
"url_key": "jumpsuits",
"level": 4,
"url_suffix": ".html",
"breadcrumbs": [
{
"category_id": 3,
"category_level": 2,
"category_name": "Clothing",
"category_url_key": "clothing",
"category_url_path": "clothing"
},
{
"category_id": 82,
"category_level": 3,
"category_name": "Jumpsuits & Rompers",
"category_url_key": "jumpsuits-rompers",
"category_url_path": "clothing/jumpsuits-rompers"
}
],
"path": "clothing/jumpsuits-rompers"
},
{
"id": 2492,
"name": "Cargo Jumpsuit",
"url_key": "cargo-jumpsuit",
"level": 5,
"breadcrumbs": [
{
"category_id": 3,
"category_name": "Clothing",
"category_url_path": "clothing"
},
{
"category_id": 82,
"category_name": "Jumpsuits & Rompers",
"category_url_path": "clothing/jumpsuits-rompers"
},
{
"category_id": 2437,
"category_name": "Jumpsuits",
"category_url_key": "jumpsuits",
}
],
"path": "clothing/jumpsuits-rompers/jumpsuits"
}
]}
let sub_category_names = []
let category_names = []
product.categories.forEach(function (category) {
category_names.push(category.name)
category.breadcrumbs.forEach(function (item) {
sub_category_names.push(item.category_name)
});
});
// for convert to string
let category_str = category_names.toString();
let str = sub_category_names.toString();
console.log("Main Categories are",category_str);
console.log("Sub Cateogries are ",str);
来源:https://stackoverflow.com/questions/65803664/seperate-some-values-from-json-object-react-jquery