Using map to access nested json in react native - javascript

I am trying to access keys and arrays in my json structure with Array.map() but I'm missing something.
Here's my JSON:
{
"payload": [
{
"id": 1,
"name": "Atta",
"brands": [
{
"id": 118,
"name": "Wheatola",
"subProducts": [
{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}
]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [
{
"id": 25,
"name": "CookStar",
"subProducts": [
{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}
]
}
]
}
I want to access payload.name, payload.brands.name(s), payloads.brands.subproducts.name(s) with Array.map() and render the values in components. How do I access nested json like using map()?
Expected output is:
Atta, Wheatola, Chakki Aata
Atta, Wheatola, Chakki Aata
Rice (Branded), Cookstar, Best Basmati
Rice (Branded), Cookstar, Extra Long Grain Basmati

You need to nest Array.map()
var data = {
"payload": [
{
"id": 1,
"name": "Atta",
"brands": [
{
"id": 118,
"name": "Wheatola",
"subProducts": [
{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}
]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [
{
"id": 25,
"name": "CookStar",
"subProducts": [
{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}
]
}
]
}
const renderData = data.payload.map((payload) => {
return payload.brands.map(brand =>{
return brand.subProducts.map(subProduct => {
return `${payload.name}, ${brand.name}, ${subProduct.name}`
}).join("\n")
}).join("\n")
}).join("\n")
console.log(renderData);

Here might be a working example (without styling or anything):
render() {
return (
<div>
{
json.payload.map(j =>
<div>
{j.name}
{j.brands.map(b =>
<div>
{b.name}
{b.subProducts.map(s =>
<div>
{s.name}
</div>)
}
</div>
)}
</div>
)
}
</div>
);
}
You probably need to style it, or combine it with a table and columns, because it just renders the values now.

You can also use forEach since you'll have to nest map calls but you expect a flat array (?) in the end :
var json = {
"payload": [{
"id": 1,
"name": "Atta",
"brands": [{
"id": 118,
"name": "Wheatola",
"subProducts": [{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [{
"id": 25,
"name": "CookStar",
"subProducts": [{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}]
}
]
}
var result = [];
json.payload.forEach(product => {
product.brands.forEach(brand => {
brand.subProducts.forEach(subProduct => {
result.push([product.name, brand.name, subProduct.name].join(', '));
});
});
});
console.log(result);

Related

Can't loop array after grouping with .reduce

I've got the following meetings object :
[
{
"id": 19,
"duration": 1.75,
"Employee": {
"name": "Jeanne",
}
},
{
"id": 20,
"duration": 1.00,
"Employee": {
"name": "Louis",
}
},
{
"id": 21,
"duration": 1.00,
"Employee": {
"name": "Jeanne",
}
}
]
I want to group it by Employee.name. Using reduce() here is what I come up with :
meetings.reduce(function (r, a) {
r[a.Employee.name] = r[a.Employee.name] || [];
r[a.Employee.name].push(a);
return r;
}
The resulting object is the following :
{
"Jeanne": [
{
"id": 19,
"duration": 1.75,
"Employee": {
"name": "Jeanne"
}
},
{
"id": 21,
"duration": 1.00,
"Employee": {
"name": "Jeanne"
}
}
],
"Louis": [
{
"id": 20,
"duration": 1.00,
"Employee": {
"name": "Louis"
}
}
]
}
If I try to map() or forEach() i cannot get the value of the element :
Array.from(thisMeeting).forEach(element => console.log(element));
return `undefined`;
Array.from-ming an Object will result in an empty array.
You'll have to iterate over the objects keys with Object.entries(thisMeeting).forEach… and grab the values inside that.

React - Filter Multidimensional array with another array

I want to return only matches results.
My array:
products: [
{
"id": 1,
"name": "Product 1",
"concepts": [
{
"id": 10,
"name": "Blabla"
},
{
"id": 15,
"name": "Zlazla"
}
]
},
{
"id": 2,
"name": "Product 2",
"concepts": [
{
"id": 14,
"name": "Gulagula"
},
{
"id": 15,
"name": "Zlazla"
}
]
}
]
I want to filter products which only have one of the concepts below.
concepts array:
['14', '15']
Couldn't solve this in an easy way.
You can try this way:
var products= [
{
"id": 1,
"name": "Product 1",
"concepts": [
{
"id": 10,
"name": "Blabla"
},
{
"id": 15,
"name": "Zlazla"
}
]
},
{
"id": 2,
"name": "Product 2",
"concepts": [
{
"id": 14,
"name": "Gulagula"
},
{
"id": 15,
"name": "Zlazla"
}
]
}
]
var products = products.filter((product) => product.concepts = product.concepts.filter( (x) => x.id == 14 || x.id == 15));
console.log(products);

How can i make json file like this when i input

How can i make the cart_items like my expetation.. just it no more.. my problem just it :D
i just wanna make my cart_items like this.. hope you are can help me thanks. did I make the wrong method? and one more thing, i wanna make the qty inside the cart_items
this is my expectation
"cart": [
{
"id": 1,
"date": "12/10/2020",
"store": {
"id": 1,
"name": "Dirumah Aja",
"promo": 1
},
"cart_items": [
{
"id": 1,
"product": {
"id": 1,
"name": "Bakso Urat",
"price": 10000,
"promo": {
"nama": "promo"
}
},
"qty": 5
}
]
}
]
and this is what I got
"cart": [
{
"cart_items": {
"name": "Steak Sapi Impor",
"price": "38000",
"stock": "4",
"image": "https://firebasestorage.googleapis.com/v0/b/francise-fb70a.appspot.com/o/steak.jpg?alt=media&token=46e0d769-96d3-440f-8edb-5fce2481ace0",
"promo": 3,
"id": 8,
"qty": 1
},
"store": {
"name": "Amanda Foods Store",
"email": "amanda#food.com",
"store_image": "https://firebasestorage.googleapis.com/v0/b/francise-fb70a.appspot.com/o/full_hd_retina.jpeg?alt=media&token=3e602e86-661b-48ee-9e9c-af9f94a170d1",
"product": [
5,
7,
8,
2
],
"store_promo": 1,
"location": {
"street_name": "Jl. Kebon Gedang II B",
"province": "Jawa Barat",
"city": "Bandung",
"post_code": "40285"
},
"id": 1
},
"date_order": "Nov 03 2020 08:48:03",
"id": 2
}
]
This is my data
data() {
return {
promo_id: [],
promo_partner: [],
products: {},
qty: 1,
cart_items: [
{}
]
};
and this is my method
addToCart() {
const date = (new Date()).toString().split(' ').splice(1,4).join(' ')
this.products.cart_items = this.product;
this.products.cart_items.qty = this.qty;
this.products.store = this.partner;
this.products.date_order = date;
console.log(this.cart_items)
axios
.post("http://localhost:3000/cart/", this.products)
.then(() => {
swal("Belanja Berhasil!", {
icon: "success",
});
})
.catch((error) => console.log(error));
}
}
You need to use .push() to add items to an array. You're replacing the array with this.product.
if (!this.products.cart_items) { // initialize cart_items if necessary
this.products.cart_items = [];
}
this.products.cart_items.push({id: this.product.id, product: this.product, qty: this.qty});

How to turn object values into new array in JavaScript

I am trying to simplify the following state:
{
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types": [
{
"slot": 1,
"type": {
"name": "poison",
"url": "https://poke"
}
},
{
"slot": 2,
"type": {
"name": "grass",
"url": "https://poke"
}
}
]}
into something like this:
{
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types": [ "poison", "grass" ]
}
Also, I would like to mention that I have an array with 151 of these. Not every object contains two types; some only contain one.
I believe that is the reason most of what I have tried so far does not work. Thank you in advance for your help.
Try using map
let obj={ name: "bulbasaur", picture: "https://raw", height: 7, weight: 69, types : [{ slot: 1, type: { name: "poison", url:"https://poke" }}]};
obj.types=obj.types.map( Type => Type.type.name);
console.log(obj.types);
I think this is what you want, you will need to add this snippet in a loop for you dataset and have it pushed into a new array:
const Obj = {
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types" : [{
"slot": 1,
"type": {
"name": "poison",
"url":"https://poke"
}}, {
"slot": 2,
"type": {
"name": "grass",
"url":"https://poke"
}}
]};
const newObj = {
...Obj,
types: Obj.types.map((el) => el.type.name),
}
console.log(newObj)
I was able to resolve what I needed by using the logic provided by Ma'moun othman.
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types" : [{
"slot": 1,
"type": {
"name": "poison",
"url":"https://poke"
}}, {
"slot": 2,
"type": {
"name": "grass",
"url":"https://poke"
}}
]};
const newObj = {
...Obj,
types: Obj.types.map((el) => el.type.name),
}
console.log(newObj)

How to get the respective JSON object based on id

how to get the respective nested JSON object based on Id. For example below is my complete JSON.
[
{
"id": 1,
"title": "ASD Headquarters",
"items": [
{
"id": 11,
"title": "San Jose",
"items": [
{
"id": 13,
"title": "Jensen Chapman's Team",
"items": [
{
"id": 14,
"title": "Jimmy John"
},
{
"id": 15,
"title": "Daniel Mills"
},
{
"id": 16,
"title": "Chris Boden"
}
]
}
]
},
{
"id": 12,
"title": "Irvine",
"items": [
{
"id": 23,
"title": "Tracey Chapman's Team",
"items": [
{
"id": 24,
"title": "San Jesus"
},
{
"id": 25,
"title": "Fat Albert"
},
{
"id": 26,
"title": "Connor McDavid"
}
]
}
]
},
{
"id": 30,
"title": "San Diego",
"items": [
{
"id": 31,
"title": "Duran Duran's Team",
"items": [
{
"id": 32,
"title": "Amberlynn Pinkerton"
},
{
"id": 33,
"title": "Tony Mejia"
},
{
"id": 34,
"title": "Richard Partridge"
},
{
"id": 35,
"title": "Elliot Stabler"
}
]
},
{
"id": 40,
"title": "Steely Dan's Team",
"items": [
{
"id": 36,
"title": "Tony Stark"
},
{
"id": 37,
"title": "Totally Rad"
},
{
"id": 38,
"title": "Matt Murdock"
},
{
"id": 39,
"title": "Stan Lee"
}
]
}
]
}
]
}
]
From the above json how do i filter only particular nested object which have id as 11 => {"id": 11} using underscore.js
Output which i required is : {
"id":11,
"title":"San Jose",
"items":[
{
"id":13,
"title":"Jensen Chapman's Team",
"items":[
{
"id":14,
"title":"Jimmy John"
},
{
"id":15,
"title":"Daniel Mills"
},
{
"id":16,
"title":"Chris Boden"
}
]
}
]
}
You can use a recursive algorithm to look for an object in the current array as well as the nested ones.
var data = [{"id":1,"title":"ASD Headquarters","items":[{"id":11,"title":"San Jose","items":[{"id":13,"title":"Jensen Chapman's Team","items":[{"id":14,"title":"Jimmy John"},{"id":15,"title":"Daniel Mills"},{"id":16,"title":"Chris Boden"}]}]},{"id":12,"title":"Irvine","items":[{"id":23,"title":"Tracey Chapman's Team","items":[{"id":24,"title":"San Jesus"},{"id":25,"title":"Fat Albert"},{"id":26,"title":"Connor McDavid"}]}]},{"id":30,"title":"San Diego","items":[{"id":31,"title":"Duran Duran's Team","items":[{"id":32,"title":"Amberlynn Pinkerton"},{"id":33,"title":"Tony Mejia"},{"id":34,"title":"Richard Partridge"},{"id":35,"title":"Elliot Stabler"}]},{"id":40,"title":"Steely Dan's Team","items":[{"id":36,"title":"Tony Stark"},{"id":37,"title":"Totally Rad"},{"id":38,"title":"Matt Murdock"},{"id":39,"title":"Stan Lee"}]}]}]}];
console.log(find(12, data));
function find(id, [head, ...tail]) {
if (!head)
return null;
return checkObj(id, head) || find(id, tail);
}
function checkObj(id, obj) {
return obj.id === id ? obj : find(id, obj.items || [])
}
This also uses parameter destructuring in order to conveniently separate the "head" of the array from its "tail".
It could also be done within a single function.
var data = [{"id":1,"title":"ASD Headquarters","items":[{"id":11,"title":"San Jose","items":[{"id":13,"title":"Jensen Chapman's Team","items":[{"id":14,"title":"Jimmy John"},{"id":15,"title":"Daniel Mills"},{"id":16,"title":"Chris Boden"}]}]},{"id":12,"title":"Irvine","items":[{"id":23,"title":"Tracey Chapman's Team","items":[{"id":24,"title":"San Jesus"},{"id":25,"title":"Fat Albert"},{"id":26,"title":"Connor McDavid"}]}]},{"id":30,"title":"San Diego","items":[{"id":31,"title":"Duran Duran's Team","items":[{"id":32,"title":"Amberlynn Pinkerton"},{"id":33,"title":"Tony Mejia"},{"id":34,"title":"Richard Partridge"},{"id":35,"title":"Elliot Stabler"}]},{"id":40,"title":"Steely Dan's Team","items":[{"id":36,"title":"Tony Stark"},{"id":37,"title":"Totally Rad"},{"id":38,"title":"Matt Murdock"},{"id":39,"title":"Stan Lee"}]}]}]}];
console.log(find(12, data));
function find(id, [head, ...tail]) {
if (!head)
return null;
if (head.id === id)
return head;
return find(id, head.items || []) || find(id, tail);
}

Categories

Resources