basic java script json child array decoding - javascript

I have been teaching myself some basic javascript the last couple of days and playing with google scripting as well as the twitter api and have come a bit unstuck on something that should probably be quite easy!
For sake of easierness of typing so my return from twitter api looks like this
[id:1
connections: "NONE"
],
[id:2
connections: ["following", "followed_by"]
]
What I am trying to do is find out out if the key 'following' exists for user 2, but I am really struggling!
The twitter api docs show an examples json as
[
{
"name": "Taylor Singletary",
"id_str": "819797",
"id": 819797,
"connections": [
"none"
],
"screen_name": "episod"
},
{
"name": "Twitter API",
"id_str": "6253282",
"id": 6253282,
"connections": [
"following",
"followed_by"
],
"screen_name": "twitterapi"
}
]
Can any point me in the correct direction?, how do I find out if following exists?
Thanks

connections: ["following", "followed_by"] is an array. To check if an array contains a special value you can use indexOf():
var a = [1, 2, "three", 44];
a.indexOf(1); // 0
a.indexOf(2); // 1
a.indexOf("three"); // 2
a.indexOf(22); // -1
So to check if "following" is in the array:
if (connections.indexOf("following") !== -1) {
// yeah!
} else {
// doh!
}
To count the objects in your example which have "following":
var o = [
{
"name": "Taylor Singletary",
"id_str": "819797",
"id": 819797,
"connections": [
"none"
],
"screen_name": "episod"
},
{
"name": "Twitter API",
"id_str": "6253282",
"id": 6253282,
"connections": [
"following",
"followed_by"
],
"screen_name": "twitterapi"
}
];
var withFollowing = o.filter(
function (i) {
return i.connections.indexOf("following") !== -1;
}
);
// filter() returns a new array
// this new array has only the elements for which the function returns true
console.log(withFollowing.lenght);

Related

Iterate through array of objects,not giving required output

given code
[
{
"data": [
{
"text_name": "test",
"text_url": "https://www.news18.com/topics/gold-prices/1",
"is_new": "1"
},
{
"text_name": "test2",
"text_url": "https://www.news18.com/topics/gold-prices/2",
"is_new": "0"
}
],
"slug": "bollywood",
"heading": "testing",
"status": "1",
"is_open_new": "1",
"order_data": "2",
"section_dropdown": "bollywood"
}
]
I want to iterate through this given code snippet and get the data.
const trendingTopicsData = trendingTopics.data
but this is showing null
Since the object in the snippet is an array, first you have to get the index of the item you want to work with (in this case the first item — index 0). Then you can iterate through the data array however you want (loop, forEach, map etc.).
Try:
const trendingTopicsData = trendingTopics[0].data
Here it is as a runnable snippet:
const trendingTopics = [
{
"data": [
{
"text_name": "test",
"text_url": "https://www.news18.com/topics/gold-prices/1",
"is_new": "1"
},
{
"text_name": "test2",
"text_url": "https://www.news18.com/topics/gold-prices/2",
"is_new": "0"
}
],
"slug": "bollywood",
"heading": "testing",
"status": "1",
"is_open_new": "1",
"order_data": "2",
"section_dropdown": "bollywood"
}
]
// Get trending topics data array
const trendingTopicsData = trendingTopics[0].data;
console.log("Data array:", trendingTopicsData)
// Iterate through each of the items in the data array
trendingTopicsData.forEach((dataItem, index) => console.log(`Data item #${index}:`, dataItem));
The object you are trying to access is inside an array. You will have to loop through the array
trendingTopics.forEach(topic => {
// do something with topic.data
})

is it possible to retrieve and print the data from a json object inside json array without using any index values and specific keys

[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
now i need to check and print the JSON Object inside the JSON Array if category is present then it should print and in future if category is changed according to that if we pass parameter the output should print we don't hard code the code
i have tried by using key values it is coming but if the key value changes it is not printing the object
EX:-
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
in the above code i have printed category object but if category changed to categories it is not printing so i want a code which can read the code and based on parameters user giving it should be print the output
Try this.
For Example:
let a = [{"id": "628ba44f5a6de600071d16fa","category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}]}]
function print (values){return (a[0][`${values}`])}
//now just pass any name like "category" or in future "categories"
print("category") //this will retrun the array.
Now modify with your requirements.
It seems you want to get the value of the key(that can be parameterized).
const jsonArray = [
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}
]
}
];
const parameter = "category";
const result = jsonArray.find(({ [parameter]: value }) => value);
if (result) {
console.log(result);
} else {
console.log(`No object found with ${parameter}`);
}
If this is not what you are looking for, then please add your code snippet for better understanding.

How can I extract nested value in JSON and initialize to a JS variable

my question is above and I am trying like for 45mins to extract the value under "distance" below, but I fail at every try. I hope you guys can help me.
{
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
So I need the value under rows --> elements --> distance then value. I tried something like this in JavaScript:
var payload = JSON.parse(body)
console.log(payload.rows["elements"].distance.value)
Thanks! :)
Süleyman Demir
let distance = payload.rows[0].elements[0].distance.value
console.log(payload)
console.log(distance)
Please note that the data is a mix of nested arrays and objects, which are different data structures in javascript. You can access an object's property by typing its name followed by a dot and the name of the property (object_name.property_name). You can access an array's element by typing the element index in square brackets next to the array's name (array_name[element_number]).
In our case we access the property "rows" which is an array of the object "payload" - payload.rows. Then we access the element number [0] of this array by typing [0] next to the property's name - payload.rows[0]. We get another object which has the property "elements" in it - payload.rows[0].elements . This property stores another array and we access its first element again -
payload.rows[0].elements[0]. We get another object and access the property "distance" which returns finally return another object that holds the property "value" we are looking for - payload.rows[0].elements[0].distance.value
Source https://eloquentjavascript.net/04_data.html
Your question was not clear, I assume that you will have multiple rows and multiple elements. There is my solution according to what I understand.
payload.rows.forEach(x=> x.elements.forEach(y => console.log(y.distance.value)))
Try like below
var body = {
"destination_addresses": ["XXXXXXXX 60, 13XXX Berlin, Germany"],
"origin_addresses": ["XXXXXXX Str. 67, 10XXX Berlin, Germany"],
"rows": [{
"elements": [{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}]
}],
"status": "OK"
};
var payload = JSON.parse(JSON.stringify(body));
payload.rows.forEach(row => row.elements.forEach(elem => console.log("Distance : ", elem.distance.value)))
I don't know exactly what you want, but you can get the distance object with something like that:
const payload = {
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
let distance = payload.rows[0].elements.map(element => {
return {
distance: element.distance
}
});
// Map returns an array, so you can get the object using the index:
console.log(distance[0]);
// If you want only the value:
console.log(distance[0].distance.value);
If you want, you can also use Object.assign or something like that to avoid getting the value by the index.
Hope it helped!
var payload = JSON.parse(body);
console.log(payload.rows[0]["elements"][0].distance.value);

How can i get an index of an Array in an Array of a Json Doc

I have a Json Doc which i get from my back end which looks like the one below. It has an emails Array which the doc under it has and email array. I need to get the index the email array is part of which has a match for an email address so i can update the doc. i used lodash before to search for a key in a array of docs before with _.find and _.indexOf but not sure how this would work in an Array of Array case.
{
"_type": "email_campaign",
"status": "Active",
"start_date": "04/17/2020",
"template_id": "template::0a2decdd-3acd-4661-9721-1a9ec0d039e6",
"summary": "Update",
"metrics": {
"first_email_sent": "",
"last_email_send": "2020-04-17T22:11:52.317Z",
"nbr_of_emails": 185,
"nbr_of_bounces": 1,
},
"history": {
"created_on": "04/17/2020 13:24:33",
},
"emails": [
{
"email": [
"DCustomer#gmail.com"
],
"track_request": "track_request::da07bd4b-b03e-4ecc-9d90-32e85cdb5b3a",
"tracking_nbr": "MD1dpjR6d"
},
{
"email": [
"ACustomer#matcocomponents.com",
"BCustomer#matcocomponents.com",
],
"track_request": "track_request::6f64cee1-d38e-4d68-94a2-c3c7d1287984",
"tracking_nbr": "YM1sMRX3nl"
},
{
"email": [
"ACustomer#gmail.com"
],
"track_request": "track_request::92606d4f-f9e6-457f-9156-167eb068f05b",
"tracking_nbr": "gj6dwIyHdE"
},
],
"_id": "3ed76589-4063-49f6-a21e-9ca16981d102"
}
You could use findIndex and includes:
const index = docs.emails.findIndex(item => item.email.includes('ACustomer#matcocomponents.com'))
try this:
emailToFind="xxxxxxxxx"
var indexes=[]
var test= res.emails.map((el1,i1)=>{
el.email.map((el2,i2)=>{
if (el2===emailToFind){
indexes.push(i1)
}
})
})

How to delete a paticular Object in an array inRethinkDB

I am Just trying to learn RethinkDB.I am little Bit Confused That how to delete an single Object in an array,What is the Exact query I have to use if i have to delete this Object
{
"name": "Ram" ,
"username": "B97bf210-c4d2d-11e6-b783-07b5fev048705"
}
from whoLikedIt Array
My data
{
"comments": [ ],
"id": "c242c74d-03d9-4963-9a22-4779facb8192" ,
.....
"views": 0 ,
"whoLikedIt": [
{
"name": "Vignesh Warar" ,
"username": "d97bf210-c42d-11e6-b783-07b5fe048705"
},
{
"name": "Ram" ,
"username": "B97bf210-c4d2d-11e6-b783-07b5fev048705"
},
]
.....
}
My Try
r.db('image').table('posts').get('c242c74d-03d9-4963-9a22-4779facb8192').update(
{whoLikedIt:r.row('whoLikedIt').filter({username:"B97bf210-c4d2d-11e6-b783-07b5fev048705"}).delete()}
)
Throws Me a error
e: Cannot nest writes or meta ops in stream operations. Use FOR_EACH instead in:
You want:
r.db('image').table('posts').get('c242c74d-03d9-4963-9a22-4779facb8192').update(function(row) {
return {whoLikedIt: row('whoLikedIt').filter(function(obj) {
return obj('username').ne("B97bf210-c4d2d-11e6-b783-07b5fev048705");
})};
})

Categories