How to access a nested object property in JSON [duplicate] - javascript

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 2 years ago.
I am trying to access nested property productTitle in below order JSON, however, could only manage to get the items using
JSON.stringify(orders[i].cart.items, null, 4);
I have tried the nested loop but to no avail. I have also tried
JSON.stringify(orders[i].cart.items.item, null, 4);
which is also not working. Missing something fundamental, I have spent hours looking through JSON docs and tutorials but could not find specific help.
[
{
"_id": "5ea5115224bf1f569c4fac96",
"user": "5ea19f4160539d264ca1e7c5",
"cart": {
"items": {
"5e92b488fc3e326b70be262d": {
"item": {
"_id": "5e92b488fc3e326b70be262d",
"productCode": "PROD002",
"productType": "Duvet",
"productTitle": "Kingsize Duvet",
"__v": 0
},
"qty": 1,
"price": 3
},
"5e92f5f9213dc863e0e97682": {
"item": {
"_id": "5e92f5f9213dc863e0e97682",
"productCode": "PROD006",
"productType": "Duvet",
"productTitle": "double-Duvet",
"__v": 0
},
"qty": 2,
"price": 5
}
},
"totalQty": 3,
"totalPrice": 8
},
"address": "London",
"name": "John Cena",
"paymentId": "ch_1Gc2KUIyQsnk8nhOTUR602KW",
"__v": 0
}
]
Please be gentle, I am a newbie!
Update:
Manage to get the nested keys and values using below iteration:
for(var i=0;i
for (var key of Object.keys(orders[i].cart.items)) {
console.log("Title: "+ orders[i].cart.items[key].item.productTitle );
console.log("Quanitity: "+ orders[i].cart.items[key].qty);
console.log(" Price: "+orders[i].cart.items[key].item.productPrice );
console.log(" Subtotal: "+orders[i].cart.items[key].item.productPrice * orders[i].cart.items[key].qty);
console.log("Total Quantity is :"+orders[i].cart.totalQty+" & Total Price: £ " + orders[i].cart.totalPrice);
}

I think you have missed fetching 5e92b488fc3e326b70be262d in your call dot reference call after items .
orders[i].cart.items['5e92f5f9213dc863e0e97682'].item.productTitle
This worked for me .
5e92b488fc3e326b70be262d is also an object in your json so you have to access 5e92b488fc3e326b70be262d object before accessing item .
'5e92f5f9213dc863e0e97682'has been added in your json as a map and not as an object. That's why not working with dot operator.
This is what I did .
this.http.get("assets/client.json").subscribe(data =>{
console.log(data[0].cart.items['5e92f5f9213dc863e0e97682'].item.productTitle);
var items = data[0].cart.items;
console.log(items['5e92f5f9213dc863e0e97682'].item.productTitle);
})
Both console statements gave double-Duvet as output .

Related

How to map through nested objects of Laravel collection in React JS

In my front-end I am trying to map through nested objects which is coming from back-end Laravel collection:
[
{
"id": 1,
"name": "Chips",
"product_categories_id": 1,
"category": {
"id": 1,
"category": "Chips",
"brand": "Bombay Sweets"
}
},
{
"id": 2,
"name": "Book",
"product_categories_id": 2,
"category": {
"id": 2,
"category": "Shoe",
"brand": "Nike",
}
}]
I want to display the product name and related category name from nested object. My approach is:
products.map((product)=>{
console.log(product.name)
product.category.map((category)=>(
console.log(category.category)
))
})
which is not working at all. I spent huge amount of time to solve yet no luck.
the error it shows:
ProductListContainer.js:58 Uncaught TypeError: item.category.map is not a function
map method works only with Array. You can use product.category.category to access the value.
Finally solved by this:
products.map((product) => {
console.log(product.name)
Object.entries(product.category).map(() => (
console.log(product.category.category, product.category.brand)
))
})

see undefined when try to parse json [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I have tried to parse this JSON file. But I see undefined.
I need to receive only value, where the key equals level1.
[{
"id": 2,
"name": "Peter",
"products": [{
"title": "first",
"price": 100
},
{
"title": "second",
"price": 200,
"desciption": [{
"level1": "good",
"level2": "bad"
},
{
"level3": "super",
"level4": "hell"
}
]
}
],
"country": "USA"
}]
const fs = require('fs');
let file = fs.readFileSync("./file.json");
let parsed = JSON.parse(file);
console.log(parsed["name"])
console.log(parsed.name);
and I see in the conlose "undefined"
Your JSON data represents an array of objects. If after parsing you want the property "name" of the first element, it's:
console.log(parsed[0]["name"])
or
console.log(parsed[0].name);

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

How to get an array inside an array?

Hi I have trouble with an array response of json.
I'm supposed to get the members of the objects. but that array is inside another array.
This is the array that is being returned.
var arr = [
[
{
"id": 4243430853,
"email": "jayduco2#gmail.com",
},
{
"id": 4227666181,
"email": "deofederickduran#gmail.com",
},
{
"id": 4227644293,
"email": "kfsucayan#gmail.com",
}
],
[
{
"id": 4243430854,
"email": "jayduco2#gmail.com",
},
{
"id": 4227666182,
"email": "deofederickduran#gmail.com",
},
{
"id": 4227644294,
"email": "kfsucayan#gmail.com",
}
]
];
How can i dig down to the values? before I would use arr[i].email, but now it doesn't work. I've tried arr[0].[i].email, but returns be the error missing name after . operator. Is there a way that I can remove that outer array?
It should be arr[i][j].email. i to loop over the array arr itself and j to loop over each sub-array.
arr[i] will give you something like this (if i == 0 for example):
[
{
"id": 4243430853,
"email": "jayduco2#gmail.com",
},
{
"id": 4227666181,
"email": "deofederickduran#gmail.com",
},
{
"id": 4227644293,
"email": "kfsucayan#gmail.com",
}
]
and then arr[i][j] will give something like this (if i == 0 and j == 2):
{
"id": 4227644293,
"email": "kfsucayan#gmail.com",
}
then you can access the email property using arr[i][j].email.
There's two ways to access objects in Javascript: using periods or using square brackets. Here, you're trying to mix the two, which works, but probably isn't the best practice. You should pick whichever is best for the situation. Here, you'd want to use the brackets:
arr[i][j]["email"];
Note that when using variables, you will always need to use brackets as opposed to periods.

JSON parsing object Object [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I have ajax call that produces this block of data
[
{
"2014-05-28": {
"date": "28",
"month": "05",
"year": "2014",
"data": [
{
"title": "Html test <!-- comm --> tesd ",
"link": "/tickets/ticket/3",
"progress": "33.33",
"creator": "Ivo Ivic",
"priority": "H"
}
]
},
"2014-05-30": {
"date": "30",
"month": "05",
"year": "2014",
"data": [
{
"title": "I ovo u petak",
"link": "/tickets/ticket/10",
"progress": "0.00",
"creator": "Ivo Ivic",
"priority": "H"
},
{
"title": "Do kraja tjedna!",
"link": "/tickets/ticket/9",
"progress": "0.00",
"creator": "Ivo Ivic",
"priority": "N"
}
]
}
},
"<div><h3>Expired deadlines</h3>\r\n <div class=\"deadline_expired\" style=\"display: block;\">\r\n\t\t<span class=\"exp_deadline_title\">\r\n\t\t\t<div class=\"exp_deadline_priority_box\" style=\"background: #e82024\"></div>\r\n\t\t\t<a class=\"dashboard_titles\" href=\"/tickets/ticket/7\" title=\"Zadaća za novi projekt\">Zadaća za novi projekt</a>\r\n\t\t</span>\r\n\r\n\t\t<span class=\"deadline_info_wrapper\">\r\n\t\t\t<div class=\"exp_deadline_icon_box\"></div>\r\n\t\t\t<div class=\"deadline_date\">\r\n <div class=\"deadline_text_color\">Deadline:</div>\r\n <div class=\"deadline\">datum :(</div>\r\n </div>\r\n\t\t\t<div class=\"deadline_no_days expired_days_style\">1 DAY AGO</div>\r\n\t\t</span>\r\n <div class=\"clear\"></div>\r\n </div>\r\n <div class=\"deadline_expired\" style=\"display: block;\">\r\n\t\t<span class=\"exp_deadline_title\">\r\n\t\t\t<div class=\"exp_deadline_priority_box\" style=\"background: #f7cf2f\"></div>\r\n\t\t\t<a class=\"dashboard_titles\" href=\"/tickets/ticket/8\" title=\"Stari zadatak\">Stari zadatak</a>\r\n\t\t</span>\r\n\r\n\t\t<span class=\"deadline_info_wrapper\">\r\n\t\t\t<div class=\"exp_deadline_icon_box\"></div>\r\n\t\t\t<div class=\"deadline_date\">\r\n <div class=\"deadline_text_color\">Deadline:</div>\r\n <div class=\"deadline\">datum :(</div>\r\n </div>\r\n\t\t\t<div class=\"deadline_no_days expired_days_style\">2 DAYS AGO</div>\r\n\t\t</span>\r\n <div class=\"clear\"></div>\r\n </div>\r\n</div>"
]
I am trying to get the 1st part (index 0) object to another object
Lets say the upper part i recived in a variable called DATA
So i am trying to get
var test= JSON.parse(DATA);
console.log('parsed: '+test[0]) // returns object Object
What i am trying to get is this
Object {the data from 1st part}
Any clues on what i am doing wrong?
Simplifying your data from json... you have [{}]
Which is an array, containing an object.
When you access the [0], you get the object. You can see the json presentation with JSON.stringify(test[0])
Your object seems to have properties with keys defined as dates. If you want to access these, either you need to know the exact date and access it with myobject["2014-05-28"] or myobject.2014-05-28 (although I'm not certain this is valid with the -'s. Would be outright wrong if the key had spaces in it).
Alternatively you could iterate over the object properties.
for (var property in object) {
if (object.hasOwnProperty(property)) {
// object[property]
}
}
Are you trying to access inner data object?
If yes then try this?
console.log(test[0]['2014-05-28'].data[0]);
and to get lets say title you would do
console.log(test[0]['2014-05-28'].data[0].title);

Categories