How to use if statement inside JSON? - javascript

How to use if statement inside JSON Here is the code:
.......................................................................................
var config =
[
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
},
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
],
//define if steps should change automatically
autoplay = false,
//timeout for the step
showtime,
//current step of the tour
step = 0,
//total number of steps
total_steps = config.length;
This is the required result something like this:
var config =
[
if(page==true) {
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}
} else {
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
}
],
//define if steps should change automatically
autoplay = false,
//timeout for the step
showtime,
//current step of the tour
step = 0,
//total number of steps
total_steps = config.length;
Actually this way is wrong and makes a JavaScript syntax error.

Validating the JSON Schema Draft-07, JSON now supports the if...then...else keywords for conditional data representation.
Here is a quick example:
{
"type": "integer",
"minimum": 1,
"maximum": 1000,
"if": { "minimum": 100 },
"then": { "multipleOf": 100 },
"else": {
"if": { "minimum": 10 },
"then": { "multipleOf": 10 }
}
}
Edits
Using the OP's example in the context, it can be written like this:
{
"if": {
"page": true
},
"then": [
{
"name": "SiteTitle",
"bgcolor": "",
"color": "",
"position": "TL",
"text": "step1",
"time": 5000
},
{
"name": "Jawal",
"bgcolor": "",
"color": "",
"text": "step2",
"position": "BL",
"time": 5000
}
],
"else": [
{
"name": "Password",
"bgcolor": "",
"color": "",
"text": "step3",
"position": "TL",
"time": 5000
}
]
}

That's regular JavaScript, not JSON. Move the if statement outside:
if (page) {
var config = [
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
}, {
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}
];
} else {
var config = [
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
];
}

you can add an if inside JSON.
const config = [
...(page ? [
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}] : [{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}]),
];

or perhaps this:
var config =
(page == true) ?
[
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}
:
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
];

You can do it this way also (not saying this is the best way but it's another way and could be useful in some scenarios)
let config = [];
if (page) {
config.push({
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
});
config.push({
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
});
} else {
config.push({
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
});
}

You can use a library jsoncode that allows you to apply logical expressions directly into JSON and get the necessary result according to the transmitted model:
import jsoncode from './jsoncode.lib.mjs';
const json_src = {
"configs [AS ARRAY]": {
"[...IF page]": [
{
"name": "SiteTitle",
"bgcolor": "",
"color": "",
"position": "TL",
"text": "step1",
"time": 5000
}, {
"name": "Jawal",
"bgcolor": "",
"color": "",
"text": "step2",
"position": "BL",
"time": 5000
}
],
"[IF !page]": {
"name": "Password",
"bgcolor": "",
"color": "",
"text": "step3",
"position": "TL",
"time": 5000
}
}
};
const configsA = jsoncode(json_src, { page: true }).configs;
const configsB = jsoncode(json_src, { page: false }).configs;
console.log('configsA:', configsA);
console.log('configsB:', configsB);
https://www.npmjs.com/package/jsoncode

Related

how to update document using aggregation

I have complex document I try to update using aggregate but it's only making copy when I use $out it's remove all other document I want to concate all other file to this and update........................................................................................................................................................................................................................................................................................................................................................................................................
db.getDb().collection(coll.seat).aggregate( [
{
'$unwind': {
'path': '$show_seats'
}
}, {
'$unwind': {
'path': '$show_seats.showByDate.shows'
}
}, {
'$unwind': {
'path': '$show_seats.showByDate.shows.showSeats'
}
}, {
'$unwind': {
'path': '$show_seats.showByDate.shows.showSeats'
}
}, {
'$unwind': {
'path': '$show_seats.showByDate.shows.showSeats.seat_details'
}
}, {
'$unwind': {
'path': '$show_seats.showByDate.shows.showSeats.seat_details.values'
}
}, {
'$match': {
'show_seats.showByDate.shows.showSeats.seat_details.values._id': ObjectId('62af61b72609bb5c0b664e7e')
}
}, {
'$addFields': {
'show_seats.showByDate.shows.showSeats.seat_details.values.seat_status': true
}
},
{
$out: 'shows'
}
])
this is my mongo db data look like
{
"_id" : ObjectId("62a43ac2d7213c7233cd1dee"),
"totalShowByDay" : "2",
"totalShowDays" : 4,
"movieId" : ObjectId("62953ba3cb6ae625ec9433e6"),
"screenId" : ObjectId("6293b9638dde2d92658d5513"),
"createdAt" : 1654930114438,
"showId" : ObjectId("62a43ac2d7213c7233cd14ed"),
"show_seats" : [
{
"showByDate" : {
"ShowDate" : "2022-06-11",
"shows" : [
{
"showTime" : "2022-06-11T10:00",
"showSeats" : [
[
{
"category" : "CLASSIC",
"seat_details" : [
{
"key" : "A",
"values" : [
{
"_id" : ObjectId("62a43ac2d7213c7233cd14ee"),
"seat_number" : "1",
"tag_name" : "A",
"seat_status" : false,
"user_id" : false,
"price" : "140",
"seats_category" : "CLASSIC",
"show_time" : "2022-06-11T10:00"
},
,
{
"_id" : ObjectId("62a43ac2d7213c7233cd14ef"),
"seat_number" : "2",
"tag_name" : "A",
"seat_status" : false,
"user_id" : false,
"price" : "140",
"seats_category" : "CLASSIC",
"show_time" : "2022-06-11T10:00"
},
{
"_id" : ObjectId("62a43ac2d7213c7233cd14f0"),
"seat_number" : "3",
"tag_name" : "A",
"seat_status" : false,
"user_id" : false,
"price" : "140",
"seats_category" : "CLASSIC",
"show_time" : "2022-06-11T10:00",,
{
"_id" : ObjectId("62a43ac2d7213c7233cd14ef"),
"seat_number" : "2",
"tag_name" : "A",
"seat_status" : false,
"user_id" : false,
"price" : "140",
"seats_category" : "CLASSIC",
"show_time" : "2022-06-11T10:00"
},
{
"_id" : ObjectId("62a43ac2d7213c7233cd14f0"),
"seat_number" : "3",
"tag_name" : "A",
"seat_status" : false,
"user_id" : false,
"price" : "140",
"seats_category" : "CLASSIC",
"show_time" : "2022-06-11T10:00"
}

Mongoose $in operator not working in node

I need to make a query where it matches a specific value of an array. Not all the values of the array but only one. I know in mongo there is a $in operator so you can match 1 value of the array.
I have written my code something like this:
const getSearch = async (req,res) => {
try{
//query = { establishment: { name: "foodtruck" }, configuration: { name: "lineal" } }
console.log(query)
let doesExist = await Kitchen.find({ "establishment": { "name": { "$in": ["foodtruck","salon"] } }})
console.log(doesExist)
}catch(err){
throw err
}
}
In my local mongo i have different objects that matches the establishment name. Here they are:
db.kitchens.find()
{ "_id" : ObjectId("6084ca4c49ddab30473a7396"), "anafes" : { "quantity" : "1" }, "norms" : [ "norm5", "norm4" ], "availableDays" : [ "4/26/2021", "4/27/2021", "4/28/2021", "4/29/2021", "4/30/2021", "5/1/2021", "5/10/2021", "5/11/2021", "5/12/2021", "5/13/2021", "5/14/2021", "5/15/2021", "5/16/2021", "5/17/2021", "5/18/2021", "5/19/2021", "5/2/2021", "5/20/2021", "5/21/2021", "5/22/2021", "5/3/2021", "5/4/2021", "5/5/2021", "5/6/2021", "5/7/2021", "5/8/2021", "5/9/2021" ], "created_at" : ISODate("2021-04-25T01:26:29.542Z"), "updated_at" : ISODate("2021-04-25T01:26:29.542Z"), "deleted_at" : null, "establishment" : { "name" : "delivery" }, "dimensions" : { "name" : "40" }, "configuration" : { "name" : "lineal" }, "pictures" : [ { "_id" : ObjectId("6084ca4c49ddab30473a7397"), "url" : "https://hood-bucket-2021.s3.sa-east-1.amazonaws.com/images/1619315274721.jpg" } ], "timePrices" : [ { "_id" : ObjectId("6084ca4c49ddab30473a7398"), "time" : "perWeek", "price" : "5000" } ], "check_in" : { "from" : "00:00", "to" : "00:00" }, "check_out" : { "from" : "00:00", "to" : "00:00" }, "ovens" : { "name" : "convection", "brand" : "adidas" }, "location" : { "city" : "Buenos Aires", "province" : "Buenos Aires", "street" : "Teodoro Garcia", "number" : "1930", "coords" : [ { "_id" : ObjectId("6084ca4c49ddab30473a7399"), "lat" : "-34.5650491", "lng" : "-58.4415115" } ], "floor" : "9", "postal" : 1426 }, "type_of_time" : [ { "_id" : ObjectId("6084ca4c49ddab30473a739a"), "time" : "perWeek" } ], "host" : ObjectId("605f4e36d8281726d9be3ad3"), "__v" : 0 }
{ "_id" : ObjectId("6089f8a7bda5898d50876791"), "anafes" : { "quantity" : "1" }, "norms" : [ "norm2", "norm3", "norm8" ], "availableDays" : [ "4/30/2021", "5/1/2021", "5/10/2021", "5/11/2021", "5/12/2021", "5/13/2021", "5/14/2021", "5/15/2021", "5/16/2021", "5/17/2021", "5/18/2021", "5/19/2021", "5/2/2021", "5/20/2021", "5/21/2021", "5/22/2021", "5/23/2021", "5/24/2021", "5/25/2021", "5/26/2021", "5/27/2021", "5/28/2021", "5/29/2021", "5/3/2021", "5/30/2021", "5/31/2021", "5/4/2021", "5/5/2021", "5/6/2021", "5/7/2021", "5/8/2021", "5/9/2021", "7/1/2021", "7/10/2021", "7/11/2021", "7/12/2021", "7/13/2021", "7/14/2021", "7/15/2021", "7/16/2021", "7/17/2021", "7/18/2021", "7/19/2021", "7/2/2021", "7/20/2021", "7/21/2021", "7/22/2021", "7/23/2021", "7/24/2021", "7/25/2021", "7/26/2021", "7/27/2021", "7/28/2021", "7/29/2021", "7/3/2021", "7/30/2021", "7/31/2021", "7/4/2021", "7/5/2021", "7/6/2021", "7/7/2021", "7/8/2021", "7/9/2021" ], "created_at" : ISODate("2021-04-28T23:56:46.101Z"), "updated_at" : ISODate("2021-04-28T23:56:46.102Z"), "deleted_at" : null, "establishment" : { "name" : "foodtruck" }, "dimensions" : { "name" : "50" }, "configuration" : { "name" : "general" }, "pictures" : [ { "_id" : ObjectId("6089f8a7bda5898d50876792"), "url" : "https://hood-bucket-2021.s3.sa-east-1.amazonaws.com/images/1619654809186.jpg" }, { "_id" : ObjectId("6089f8a7bda5898d50876793"), "url" : "https://hood-bucket-2021.s3.sa-east-1.amazonaws.com/images/1619654809259.jpg" } ], "timePrices" : [ { "_id" : ObjectId("6089f8a7bda5898d50876794"), "time" : "perDay", "price" : "10000" } ], "check_in" : { "from" : "10:00", "to" : "12:00" }, "check_out" : { "from" : "15:00", "to" : "17:00" }, "ovens" : { "name" : "static", "brand" : "adidas" }, "location" : { "city" : "buenos aires", "coords" : [ { "_id" : ObjectId("6089f8a7bda5898d50876795"), "lat" : "-34.5659098", "lng" : "-58.43880350000001" } ], "province" : "buenos aires", "street" : "Olleros", "number" : "1870", "floor" : "4", "postal" : 1426 }, "type_of_time" : [ { "_id" : ObjectId("6089f8a7bda5898d50876796"), "time" : "perDay" } ], "host" : ObjectId("605f4e36d8281726d9be3ad3"), "__v" : 0 }
{ "_id" : ObjectId("608a09e29eda52a6cdc7d663"), "anafes" : { "quantity" : "1" }, "norms" : [ "norm1", "norm2", "norm4" ], "availableDays" : [ "4/30/2021", "6/1/2021", "6/10/2021", "6/11/2021", "6/12/2021", "6/13/2021", "6/14/2021", "6/15/2021", "6/16/2021", "6/17/2021", "6/18/2021", "6/19/2021", "6/2/2021", "6/20/2021", "6/21/2021", "6/22/2021", "6/23/2021", "6/24/2021", "6/25/2021", "6/26/2021", "6/27/2021", "6/28/2021", "6/29/2021", "6/3/2021", "6/30/2021", "6/4/2021", "6/5/2021", "6/6/2021", "6/7/2021", "6/8/2021", "6/9/2021" ], "created_at" : ISODate("2021-04-29T00:47:45.376Z"), "updated_at" : ISODate("2021-04-29T00:47:45.376Z"), "deleted_at" : null, "establishment" : { "name" : "foodtruck" }, "dimensions" : { "name" : "50" }, "configuration" : { "name" : "lineal" }, "pictures" : [ { "_id" : ObjectId("608a09e29eda52a6cdc7d664"), "url" : "https://hood-bucket-2021.s3.sa-east-1.amazonaws.com/images/1619659217736.jpg" }, { "_id" : ObjectId("608a09e29eda52a6cdc7d665"), "url" : "https://hood-bucket-2021.s3.sa-east-1.amazonaws.com/images/1619659217747.jpg" }, { "_id" : ObjectId("608a09e29eda52a6cdc7d666"), "url" : "https://hood-bucket-2021.s3.sa-east-1.amazonaws.com/images/1619659217668.jpg" } ], "timePrices" : [ { "_id" : ObjectId("608a09e29eda52a6cdc7d667"), "time" : "perDay", "price" : "5000" }, { "_id" : ObjectId("608a09e29eda52a6cdc7d668"), "time" : "perWeek", "price" : "15000" } ], "check_in" : { "from" : "07:00", "to" : "08:00" }, "check_out" : { "from" : "14:00", "to" : "20:00" }, "ovens" : { "name" : "convection", "brand" : "super", "model" : "adibas" }, "location" : { "city" : "BUenos aires", "coords" : [ { "_id" : ObjectId("608a09e29eda52a6cdc7d669"), "lat" : "-34.5793959", "lng" : "-58.40673389999999" } ], "province" : "Buenos aires", "street" : "Avenida del libertador", "number" : "2550", "floor" : "10", "postal" : 1426 }, "type_of_time" : [ { "_id" : ObjectId("608a09e29eda52a6cdc7d66a"), "time" : "perDay" }, { "_id" : ObjectId("608a09e29eda52a6cdc7d66b"), "time" : "perWeek" } ], "host" : ObjectId("605f4e36d8281726d9be3ad3"), "__v" : 0 }
But when I run this query:
let doesExist = await Kitchen.find({ "establishment": { "name": { "$in": ["foodtruck","salon"] } }})
it does not match anything, but if I run this query:
let doesExist = await Kitchen.find({ "establishment": { "name": "foodtruck" }})
It does match. I don't understand what I am doing wrong, or why the $in operator is not.
working.
Can someone help me?????????
let doesExist = await Kitchen.find({"establishment.name": {"$in": ["foodtruck","salon"]}})

How to make unique array in javascript

I have an array of objects.
I need to get an array with a unique website name with the newest date.
Sample data
"data" : [
{
"position" : 2,
"website" : "abc.com",
"owned" : false,
"date" : "2020-05-06",
"dateTime" : ISODate("2020-05-06T00:00:00.000Z")
},
{
"position" : 3,
"website" : "qwe.com",
"owned" : false,
"date" : "2020-05-06",
"dateTime" : ISODate("2020-05-06T00:00:00.000Z")
},
{
"position" : 1,
"website" : "qwe.com",
"owned" : false,
"date" : "2020-04-06",
"dateTime" : ISODate("2020-04-06T00:00:00.000Z")
},
{
"position" : 6,
"website" : "xyz.agency",
"owned" : false,
"date" : "2020-05-06",
"dateTime" : ISODate("2020-05-06T00:00:00.000Z")
},
{
"position" : 4,
"website" : "opq.com",
"owned" : true,
"date" : "2020-05-06",
"dateTime" : ISODate("2020-05-06T00:00:00.000Z")
},
{
"position" : 2,
"website" : "opq.com",
"owned" : true,
"date" : "2020-05-06",
"dateTime" : ISODate("2020-05-06T00:00:00.000Z")
},
{
"position" : 4,
"website" : "opq.com",
"owned" : true,
"date" : "2020-04-01",
"dateTime" : ISODate("2020-04-01T00:00:00.000Z")
}
]
Based on DateTime, position, and website. Need a MongoDB query or Javascript code.
(It's fine with DateTime and website. But getting stuck with position)
(Extracting the object from which have the highest date and unique website name with top position)
Expected response
"data" : [
{
"position" : 2,
"website" : "abc.com",
"owned" : false,
"date" : "2020-05-06",
"dateTime" : ISODate("2020-05-06T00:00:00.000Z")
},
{
"position" : 3,
"website" : "qwe.com",
"owned" : false,
"date" : "2020-05-06",
"dateTime" : ISODate("2020-05-06T00:00:00.000Z")
},
{
"position" : 6,
"website" : "xyz.agency",
"owned" : false,
"date" : "2020-05-06",
"dateTime" : ISODate("2020-05-06T00:00:00.000Z")
},
{
"position" : 2,
"website" : "opq.com",
"owned" : true,
"date" : "2020-05-06",
"dateTime" : ISODate("2020-05-06T00:00:00.000Z")
}
],
Using the below utility you can achieve the required output in javascript. Hope this will help
const getUniqueWebsites = data => {
return data.reduce((result, d) => {
if(result[d.website]) {
if(new Date(result[d.website].dateTime).getTime() < new Date(d.dateTime).getTime()){
result[d.website] = d;
}
else if(new Date(result[d.website].dateTime).getTime() === new Date(d.dateTime).getTime() &&
(result[d.website].position) > d.position){
result[d.website] = d;
}
} else {
result[d.website] = d;
}
return result;
},{})
}
let data = [
{
"position": 2,
"website": "abc.com",
"owned": false,
"date": "2020-05-06",
"dateTime": "2020-05-06T00:00:00.000Z"
},
{
"position": 3,
"website": "qwe.com",
"owned": false,
"date": "2020-05-06",
"dateTime": "2020-05-06T00:00:00.000Z"
},
{
"position": 1,
"website": "qwe.com",
"owned": false,
"date": "2020-04-06",
"dateTime": "2020-04-06T00:00:00.000Z"
},
{
"position": 6,
"website": "xyz.agency",
"owned": false,
"date": "2020-05-06",
"dateTime": "2020-05-06T00:00:00.000Z"
},
{
"position": 4,
"website": "opq.com",
"owned": true,
"date": "2020-05-06",
"dateTime": "2020-05-06T00:00:00.000Z"
},
{
"position": 2,
"website": "opq.com",
"owned": true,
"date": "2020-05-06",
"dateTime": "2020-05-06T00:00:00.000Z"
},
{
"position": 4,
"website": "opq.com",
"owned": true,
"date": "2020-04-01",
"dateTime": "2020-04-01T00:00:00.000Z"
}
]
let result = getUniqueWebsites(data)
console.log(Object.values(result))
If you want to do from JS level (warning! low performance):
var maxDate = {}; // temporary variable to store latest date of a website
var websites = data
.map(entry => {
if ((maxDate[entry.website] || 0) < entry.dateTime.getTime()) {
maxDate[entry.website] = entry.dateTime.getTime();
}
return entry;
})
.filter(entry => {
return maxDate[entry.website] === entry.dateTime.getTime();
});
If you want to do that with mongodb query: Select Max() with "group by" in mongodb

TypeError: Cannot read property '0' of undefined while accessing "photo_reference" property

Below is the JSON i get from the google places API. Parsing the Json with JSON.parse(body). The "results" key is an array of Objects that i am looping through to access the property of photos. Hope the code is clearer now. I have pasted in the valid JSON that i am getting from the api call.
{
"html_attributions" : [],
"next_page_token" : "CqQCGwEAAI5PpCTJI6Qoa1CD9iA4EpJha6t0gMlZ3I3DpOIVgE1BUYh5NNI0lXRuvAltI8RhOilTNJggXsR3TEP2C6hoIsibEWZXnZClbEcZzes7LGqJuQ0heJWipe7RNbxq8S8zuao1HWfECs11i44WO0Luv-4bYx5GlCEj6Wl07LitkzwG4u0e4FyIHogyaShky5Awd44ZyOcqKzy7wYBr7p37j6A6PMdR7zn7cMWQKiVolfHQbFZerVJ3JJ5MiKSshocG189wPKjqJzSACE6W19LmZ7TIMB9qm7jQANNQStrsq7rYAWIBQ-UqJ_6Hv9jv1xL7eRQ9bkyR17u7xPZWfeCU69u_PQmGvuvSWNJDvNUuoI-uwLc_RhgTZp26kyzMlXwYHRIQXy13ridwzgvlBU8ez_y-WBoUcBN7UvN8Q8iuDyS_LjXEWmT_sIk",
"results" : [
{
"geometry" : {
"location" : {
"lat" : 28.615572,
"lng" : 77.3468
},
"viewport" : {
"northeast" : {
"lat" : 28.6169209802915,
"lng" : 77.34814898029151
},
"southwest" : {
"lat" : 28.6142230197085,
"lng" : 77.34545101970849
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id" : "dea8496f678dc1f01381a85298e37a0905a3ca11",
"name" : "Malabar Junction Restaurant",
"opening_hours" : {
"open_now" : true,
"weekday_text" : []
},
"photos" : [
{
"height" : 746,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/117230637789134827076/photos\"\u003eSwati\u003c/a\u003e"
],
"photo_reference" : "CmRaAAAArbpjr1fjNp2Fc4ww8Vkgrzzzt5aHEvACzEZFa-XCJU3Fw2JqFLSDo64jlFWwDZwdYaFP_cIgdqI37TJ25mVB2W_rtoTv_aI0LJGgnh_P4-UF7u45ZvqdM-bE4ljYD2yyEhDjv-4AWC5AKcE713GL1qAsGhQjAN2oS1KWv52f8XsjEK3Pmnv53w",
"width" : 750
}
],
"place_id" : "ChIJx6qqqj3lDDkRcBw22oTfWgk",
"reference" : "CmRRAAAAZBpNfAiO2G_y57bLoFTSM28MG4xUi-VAg3kJgV2ZzksdhpzySwxdPNdPP1paEIE46i70oxgLHliUcEjxalukNEyhN85J-ryRbXVVMkg4Tz-MGBGhgVur7SV5b4IFePnfEhABXu9pHswL4Up5w-k9td94GhSDs13DRQVxPOpI8iWqUbLyd_WJUg",
"scope" : "GOOGLE",
"types" : [ "restaurant", "food", "point_of_interest", "establishment" ],
"vicinity" : "62, 8, Rani Jhansi Marg, Block 10, Sector 10, Noida"
}
],
"status" : "OK"
}
Trying to Access the photo_reference property like so
let resultJSON = JSON.parse(body);
let results = resultJSON["results"];
for (var i = 0; i < results.length; i++) {
let name = results[i]["name"];
console.log(results[i].photos[0].photo_reference);
}
Here is a snippet that shows your updated code is working.
let resultJSON = {
"html_attributions": [],
"next_page_token": "CqQCGwEAAI5PpCTJI6Qoa1CD9iA4EpJha6t0gMlZ3I3DpOIVgE1BUYh5NNI0lXRuvAltI8RhOilTNJggXsR3TEP2C6hoIsibEWZXnZClbEcZzes7LGqJuQ0heJWipe7RNbxq8S8zuao1HWfECs11i44WO0Luv-4bYx5GlCEj6Wl07LitkzwG4u0e4FyIHogyaShky5Awd44ZyOcqKzy7wYBr7p37j6A6PMdR7zn7cMWQKiVolfHQbFZerVJ3JJ5MiKSshocG189wPKjqJzSACE6W19LmZ7TIMB9qm7jQANNQStrsq7rYAWIBQ-UqJ_6Hv9jv1xL7eRQ9bkyR17u7xPZWfeCU69u_PQmGvuvSWNJDvNUuoI-uwLc_RhgTZp26kyzMlXwYHRIQXy13ridwzgvlBU8ez_y-WBoUcBN7UvN8Q8iuDyS_LjXEWmT_sIk",
"results": [{
"geometry": {
"location": {
"lat": 28.615572,
"lng": 77.3468
},
"viewport": {
"northeast": {
"lat": 28.6169209802915,
"lng": 77.34814898029151
},
"southwest": {
"lat": 28.6142230197085,
"lng": 77.34545101970849
}
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id": "dea8496f678dc1f01381a85298e37a0905a3ca11",
"name": "Malabar Junction Restaurant",
"opening_hours": {
"open_now": true,
"weekday_text": []
},
"photos": [{
"height": 746,
"html_attributions": [
"\u003ca href=\"https://maps.google.com/maps/contrib/117230637789134827076/photos\"\u003eSwati\u003c/a\u003e"
],
"photo_reference": "CmRaAAAArbpjr1fjNp2Fc4ww8Vkgrzzzt5aHEvACzEZFa-XCJU3Fw2JqFLSDo64jlFWwDZwdYaFP_cIgdqI37TJ25mVB2W_rtoTv_aI0LJGgnh_P4-UF7u45ZvqdM-bE4ljYD2yyEhDjv-4AWC5AKcE713GL1qAsGhQjAN2oS1KWv52f8XsjEK3Pmnv53w",
"width": 750
}],
"place_id": "ChIJx6qqqj3lDDkRcBw22oTfWgk",
"reference": "CmRRAAAAZBpNfAiO2G_y57bLoFTSM28MG4xUi-VAg3kJgV2ZzksdhpzySwxdPNdPP1paEIE46i70oxgLHliUcEjxalukNEyhN85J-ryRbXVVMkg4Tz-MGBGhgVur7SV5b4IFePnfEhABXu9pHswL4Up5w-k9td94GhSDs13DRQVxPOpI8iWqUbLyd_WJUg",
"scope": "GOOGLE",
"types": ["restaurant", "food", "point_of_interest", "establishment"],
"vicinity": "62, 8, Rani Jhansi Marg, Block 10, Sector 10, Noida"
}],
"status": "OK"
}
let results = resultJSON["results"];
for (var i = 0; i < results.length; i++) {
let name = results[i]["name"];
console.log(results[i].photos[0].photo_reference);
}

Count in Firebase JavaScript

I have a sample JSON object below:
{
"product" : [ {
"description" : "This ball has air it.",
"id" : "product0",
"name" : "football",
"price" : 10
}, {
"description" : "Can kick upto long distance.",
"id" : "product1",
"name" : "soccer boots",
"price" : 5
}, {
"description" : "Long socks",
"id" : "product2",
"name" : "stockings",
"price" : 2
}, {
"description" : "This ball has air it.",
"id" : "product3",
"name" : "gloves",
"price" : 3
}, {
"description" : "Wear it pls.",
"id" : "product4",
"name" : "jersey",
"price" : 12
} ]
}
What can be the shortest way to find the number (count) of products in JavaScript? Does Firebase provide any query in JavaScript to find the count in an object?
Here is a simple solution. Just get the length of required array from the JSON Object.
var json = {
"product": [{
"description": "This ball has air it.",
"id": "product0",
"name": "football",
"price": 10
}, {
"description": "Can kick upto long distance.",
"id": "product1",
"name": "soccer boots",
"price": 5
}, {
"description": "Long socks",
"id": "product2",
"name": "stockings",
"price": 2
}, {
"description": "This ball has air it.",
"id": "product3",
"name": "gloves",
"price": 3
}, {
"description": "Wear it pls.",
"id": "product4",
"name": "jersey",
"price": 12
}]
};
console.log(json.product.length);
Incase of JSON string: Get the length like this
var json = '{ "product" : [ {"description" : "This ball has air it.","id" : "product0","name" : "football","price" : 10 }, {"description" : "Can kick upto long distance.","id" : "product1","name" : "soccer boots","price" : 5 }, {"description" : "Long socks","id" : "product2","name" : "stockings","price" : 2 }, {"description" : "This ball has air it.","id" : "product3","name" : "gloves","price" : 3 }, {"description" : "Wear it pls.","id" : "product4","name" : "jersey","price" : 12 } ]}';
var t = JSON.parse(json);
console.log(t.product.length);
You can save the object on JavaScript variable
var myData = {
"product" : [ {
"description" : "This ball has air it.",
"id" : "product0",
"name" : "football",
"price" : 10
}, {
"description" : "Can kick upto long distance.",
"id" : "product1",
"name" : "soccer boots",
"price" : 5
}, {
"description" : "Long socks",
"id" : "product2",
"name" : "stockings",
"price" : 2
}, {
"description" : "This ball has air it.",
"id" : "product3",
"name" : "gloves",
"price" : 3
}, {
"description" : "Wear it pls.",
"id" : "product4",
"name" : "jersey",
"price" : 12
} ]
}
Now you can get length
console.log(myData.product.length);

Categories