Javascript Map through Array of Objects - javascript

I am able to print out tmdb_popularity but unable to map/print out with provider(netflix).
I believe I am mapping through {} incorrectly.
movie.offers[0].provider_id failed as well.
Also, is there a way to map out only scoring by 'provider_type:tmdb:score' > 8 for example?
Since tmdb:score is Object.value instead of key is it not feasible?
Thank you.
const JustWatch = require ("justwatch-api")
const netflixId = 8;
function print_result (name, result) {
console.log(name+":");
console.log(JSON.stringify(result, null, 4));
console.log("\n\n\n\n");
}
(async function(){
var justwatch = new JustWatch();
var searchResult = await justwatch.search('a');
searchResult.items.map(function(movie){
if(movie.offers.provider_id == netflixId){
print_result("search", searchResult)
}
})
searchResult.items.map(function(movie){
if(movie.tmdb_popularity > 20){
print_result("search",searchResult)
}
})
}) ();
What the JSON data looks like from (JustWatch API)
{
"total_results": 27468,
"items": [
{
"jw_entity_id": "ts80908",
"id": 80908,
"title": "A Very English Scandal",
"tmdb_popularity": 3.422,
"object_type": "show",
"offers": [
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 9,
"currency": "USD",
"urls": {
"standard_web": "https://www.amazon.com/gp/product/B07DX9DKP5?camp=1789&creativeASIN=B07DX9DKP5&ie=UTF8&linkCode=xm2&tag=justwatch09-20",
"deeplink_android_tv": "intent://watch.amazon.com/watch?asin=B07DX9DKP5&time=0&territory=US#Intent;package=com.amazon.amazonvideo.livingroom;scheme=https;end"
},
"subtitle_languages": [
"en"
],
"presentation_type": "sd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
},
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 9,
"currency": "USD",
"urls": {
"standard_web": "https://www.amazon.com/gp/product/B07DX9DKP5?camp=1789&creativeASIN=B07DX9DKP5&ie=UTF8&linkCode=xm2&tag=justwatch09-20",
"deeplink_android_tv": "intent://watch.amazon.com/watch?asin=B07DX9DKP5&time=0&territory=US#Intent;package=com.amazon.amazonvideo.livingroom;scheme=https;end"
},
"subtitle_languages": [
"en"
],
"presentation_type": "hd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
},
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 9,
"currency": "USD",
"urls": {
"standard_web": "https://www.amazon.com/gp/product/B07DX8CSSQ?camp=1789&creativeASIN=B07DX8CSSQ&ie=UTF8&linkCode=xm2&tag=justwatch09-20",
"deeplink_android_tv": "intent://watch.amazon.com/watch?asin=B07DX8CSSQ&time=0&territory=US#Intent;package=com.amazon.amazonvideo.livingroom;scheme=https;end",
"deeplink_fire_tv": "intent://com.amazon.tv.launcher/detail?provider=aiv&providerId=B07DX8CSSQ#Intent;package=com.amazon.tv.launcher;scheme=amzn;end",
"deeplink_tvos": "aiv://aiv/watch?asin=B07DX8CSSQ&territory=US&time=auto"
},
"subtitle_languages": [
"en"
],
"presentation_type": "4k",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-06_9",
"date_created": "2019-09-06"
}
],
"scoring": [
{
"provider_type": "tmdb:score",
"value": 8.1
},
{
"provider_type": "imdb:score",
"value": 7.8
},
{
"provider_type": "tmdb:popularity",
"value": 3.422
}
]
},
{
"jw_entity_id": "tm205151",
"id": 205151,
"title": "Alpha",
"full_path": "/us/movie/alpha-2015",
"full_paths": {
"MOVIE_DETAIL_OVERVIEW": "/us/movie/alpha-2015"
},
"poster": "/poster/139203407/{profile}",
"original_release_year": 2015,
"tmdb_popularity": 0.878,
"object_type": "movie",
"offers": [
{
"monetization_type": "flatrate",
"provider_id": 25,
"urls": {
"standard_web": "https://www.fandor.com/films/alpha"
},
"presentation_type": "hd",
"date_provider_id": "2016-06-13_25",
"date_created": "2016-06-13"
},
{
"monetization_type": "flatrate",
"provider_id": 25,
"urls": {
"standard_web": "https://www.fandor.com/films/alpha"
},
"presentation_type": "sd",
"date_provider_id": "2016-06-13_25",
"date_created": "2016-06-13"
},
{
"monetization_type": "flatrate",
"provider_id": 199,
"currency": "USD",
"urls": {
"standard_web": "https://www.amazon.com/gp/product/B01M7O3UQU?camp=1789&creativeASIN=B01M7O3UQU&ie=UTF8&linkCode=xm2&tag=justwatch09-20",
"deeplink_android_tv": "intent://watch.amazon.com/watch?asin=B01M7O3UQU&time=0&territory=US#Intent;package=com.amazon.amazonvideo.livingroom;scheme=https;end",
"deeplink_fire_tv": "intent://com.amazon.tv.launcher/detail?provider=aiv&providerId=B01M7O3UQU#Intent;package=com.amazon.tv.launcher;scheme=amzn;end",
"deeplink_tvos": "aiv://aiv/watch?asin=B01M7O3UQU&territory=US&time=auto"
},
"presentation_type": "sd",
"date_provider_id": "2019-06-19_199",
"date_created": "2019-06-19"
}
],
"scoring": [
{
"provider_type": "tmdb:popularity",
"value": 0.878
},
{
"provider_type": "tmdb:id",
"value": 333465
},
{
"provider_type": "tmdb:score",
"value": 7
},
{
"provider_type": "imdb:score",
"value": 7.7
}
]
},
....

Here Try this
searchResult.items.map(function(movie){
movie.offers.forEach(offer => {
if(offer.provider_id == netflixId){
print_result("search", searchResult)
}
})
})

forEach is better here instead of map as you are not returning in map function. Use find function to search for offer.
searchResult.items.forEach(function(movie) {
const offer = movie.offers.find(offer => offer.provider_id == netflixId);
if(offer){
print_result("search", movie)
print_result("offer", offer)
}
})

Related

How to structure and all data in the objective from Json at App script

The JSON data I am working on it. This is coming from Facebook ad API. This is being build for google data studio connector
{
"data": [
{
"adcreatives": {
"data": [
{
"actor_id": "8834759718540",
"id": "538"
}
]
},
"insights": {
"data": [
{
"ad_id": "34536578578",
"impressions": "89108",
"actions": [
{
"action_type": "comment",
"value": "02"
},
{
"action_type": "post",
"value": "03"
}
],
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
},
"created_time": "2022-06-10T22:59:33+0600",
"id": "34536578578"
},
{
"adcreatives": {
"data": [
{
"actor_id": "7834759718970",
"id": "342"
}
]
},
"insights": {
"data": [
{
"ad_id": "238509545896206",
"impressions": "57803",
"actions": [
{
"action_type": "post_engagement",
"value": "2102"
},
{
"action_type": "page_engagement",
"value": "03"
}
],
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
},
"created_time": "2022-06-11T22:59:33+0600",
"id": "238509545896206"
}
],
"paging": {
"cursors": {
"before": "dfgdfgdfgdfsdgdfgdfgdfgdfgdgdg",
"after": "yuyuyuyutyuytuyutytynfrgersggsgs"
}
}
}
Here is the JavaScript code I have used in google app script but it is showing error. I know it is totally wrong
var data = {data: parseData.data.map(({actions, ...rest}) => ({...rest,...Object.fromEntries(actions.map(({action_type, value}) =>[action_type, value]))}))};
console.log(data);
Output should be like the following way so that I can get all the data in objective
{
"data": [
{
"actor_id": "8834759718540",
"id": "538",
"ad_id": "34536578578",
"impressions": "89108",
"comment": "02",
"post": "03",
"date_start": "2022-06-11",
"date_stop": "2022-07-10",
"created_time": "2022-06-10T22:59:33+0600"
},
{
"actor_id": "7834759718970",
"id": "342",
"ad_id": "238512373324806",
"impressions": "57803",
"post_engagement": "2102",
"page_engagement": "03",
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
"created_time": "2022-06-11T22:59:33+0600"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MQZDZD"
}
}
}
You can try the code below, but it only works if adcreatives.data and insights.data have only 1 element :
let part = data.data.map(item => ({
"actor_id": item.adcreatives.data.at(0).actor_id,
"id": item.adcreatives.data.at(0).id,
"ad_id": item.insights.data.at(0).ad_id,
"impressions": item.insights.data.at(0).impressions,
"comment": item.insights.data.at(0).actions.at(0).value,
"post": item.insights.data.at(0).actions.at(1).value,
"date_start": item.insights.data.at(0).date_start,
"date_stop": item.insights.data.at(0).date_stop,
"created_time": item.created_time
}));
let result = {
data: part,
paging: data.paging
}
console.log(result);

Need to get each "link" entry from nested json using js

There is a json code. Consisting by type:
{"123":{...},"321":{...}}
In it, you need to get "links" from each entry. I couldn't understand this note, please help me.
{
"3782474584475521065": {
"listingid": "3782474584475521065",
"price": 16,
"asset": {
"currency": 0,
"appid": 730,
"contextid": "2",
"id": "25996697315",
"amount": "1",
"market_actions": [
{
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D2354938592644984102",
"name": "Осмотреть в игре…"
}
]
}
},
"3782474584475520325": {
"listingid": "3782474584475520325",
"price": 16,
"asset": {
"currency": 0,
"appid": 730,
"contextid": "2",
"id": "25996698023",
"amount": "1",
"market_actions": [
{
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D9866835690490179400",
"name": "Осмотреть в игре…"
}
]
}
}
}
Return an array of objects {id:link}
const data = {
"3782474584475521065": {
"listingid": "3782474584475521065",
"price": 16,
"asset": {
"currency": 0,
"appid": 730,
"contextid": "2",
"id": "25996697315",
"amount": "1",
"market_actions": [
{
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D2354938592644984102",
"name": "Осмотреть в игре…"
}
]
}
},
"3782474584475520325": {
"listingid": "3782474584475520325",
"price": 16,
"asset": {
"currency": 0,
"appid": 730,
"contextid": "2",
"id": "25996698023",
"amount": "1",
"market_actions": [
{
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D9866835690490179400",
"name": "Осмотреть в игре…"
}
]
}
}
}
const result = Object.entries(data).map(([key, {asset, ...rest}]) => ({[key]: asset.market_actions[0].link}))
console.log(result)
If I understood your question correctly, you need to extract the links from the json text. This is a solution:
const a = {
"3782474584475521065": {
listingid: "3782474584475521065",
price: 16,
asset: {
currency: 0,
appid: 730,
contextid: "2",
id: "25996697315",
amount: "1",
market_actions: [
{
link: "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D2354938592644984102",
name: "Осмотреть в игре…",
},
],
},
},
"3782474584475520325": {
listingid: "3782474584475520325",
price: 16,
asset: {
currency: 0,
appid: 730,
contextid: "2",
id: "25996698023",
amount: "1",
market_actions: [
{
link: "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D9866835690490179400",
name: "Осмотреть в игре…",
},
],
},
},
};
// get links from a
const links = Object.values(a).map(({ asset }) => {
const { market_actions } = asset;
const { link } = market_actions[0];
return link;
});
console.log(links);
This simply iterates through the object's values and accesses the link values through object extraction.

Javascript Object - Map through object and filter value

Currently, I am able to retrieve list of shows provided by Netflix.
However my score filter is not returning what I want.
I want to return a list with tmdb:score of 8 or greater.
Since the data structure (stored in the searchResult variable) is splitting provider_type and value, I am getting any score 8 or greater at the moment.
Is there a way to do this?
If possible, combine it with my Netflix provider function to return Netflix shows with tmdb:score of 8 or greater?
Thank you.
Node JS File
const JustWatch = require("justwatch-api")
const netflixId = 8;
function print_result (name, result) {
console.log(name+":");
console.log(JSON.stringify(result, null, 4));
console.log("\n\n\n\n");
}
(async function(){
var justwatch = new JustWatch();
var searchResult = await justwatch.search('a');
searchResult.items.map(function(movie){
movie.offers.forEach(offer => {
if(offer.provider_id === netflixId){
print_result("search", searchResult)
}
})
})
searchResult.items.map(function(movie){
movie.scoring.filter(score =>{
if(score.provider_type ==="tmdb:score" && score.value > 8) {
print_result("search", searchResult)
}
})
})
}) ();
Data structure (as stored in the searchResult variable, an object containing a count total_results and an array items of objects, each representing a movie)
{
"total_results": 27476,
"items": [
{
"jw_entity_id": "ts80908",
"id": 80908,
"title": "A Very English Scandal",
"full_path": "/us/tv-show/a-very-english-scandal",
"full_paths": {
"SHOW_DETAIL_OVERVIEW": "/us/tv-show/a-very-english-scandal"
},
"poster": "/poster/60368458/{profile}",
"original_release_year": 2018,
"tmdb_popularity": 3.422,
"object_type": "show",
"offers": [
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 9,
"currency": "USD",
"subtitle_languages": [
"en"
],
"presentation_type": "sd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
},
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 9,
"currency": "USD",
"subtitle_languages": [
"en"
],
"presentation_type": "hd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
}
],
"scoring": [
{
"provider_type": "imdb:score",
"value": 7.8
},
{
"provider_type": "tmdb:popularity",
"value": 3.422
},
{
"provider_type": "tmdb:score",
"value": 8.1
}
]
},
{
"jw_entity_id": "tm205151",
"id": 205151,
"title": "Alpha",
"full_path": "/us/movie/alpha-2015",
"full_paths": {
"MOVIE_DETAIL_OVERVIEW": "/us/movie/alpha-2015"
},
....
If you just want a filtered array of movie objects with tmdb:score>=8.0, here's a snippet to demonstrate (Note that I've mocked an object in the same format as yours with an items array of just two almost identical objects, one with the score>8.0 and one with the score<8.0 for the purpose of demonstration):
const searchResult = {
"total_results": 27476,
"items": [
{
"jw_entity_id": "ts80908",
"id": 80908,
"title": "A Very English Scandal",
"full_path": "/us/tv-show/a-very-english-scandal",
"full_paths": {
"SHOW_DETAIL_OVERVIEW": "/us/tv-show/a-very-english-scandal"
},
"poster": "/poster/60368458/{profile}",
"original_release_year": 2018,
"tmdb_popularity": 3.422,
"object_type": "show",
"offers": [
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 9,
"currency": "USD",
"subtitle_languages": [
"en"
],
"presentation_type": "sd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
},
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 9,
"currency": "USD",
"subtitle_languages": [
"en"
],
"presentation_type": "hd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
}
],
"scoring": [
{
"provider_type": "imdb:score",
"value": 7.8
},
{
"provider_type": "tmdb:popularity",
"value": 3.422
},
{
"provider_type": "tmdb:score",
"value": 8.1
}
]
},{
"jw_entity_id": "ts80909",
"id": 80908,
"title": "Some Other Title",
"full_path": "/us/tv-show/a-very-english-scandal",
"full_paths": {
"SHOW_DETAIL_OVERVIEW": "/us/tv-show/a-very-english-scandal"
},
"poster": "/poster/60368458/{profile}",
"original_release_year": 2018,
"tmdb_popularity": 3.422,
"object_type": "show",
"offers": [
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 9,
"currency": "USD",
"subtitle_languages": [
"en"
],
"presentation_type": "sd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
},
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 9,
"currency": "USD",
"subtitle_languages": [
"en"
],
"presentation_type": "hd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
}
],
"scoring": [
{
"provider_type": "imdb:score",
"value": 7.8
},
{
"provider_type": "tmdb:popularity",
"value": 3.422
},
{
"provider_type": "tmdb:score",
"value": 7.9
}
]
}]
}
const desiredMovies = searchResult.items.filter(movie => {
let tmdbScoring = movie.scoring.find(scoringObj => scoringObj.provider_type==="tmdb:score");
return tmdbScoring && tmdbScoring.value>=8.0;
})
console.log(desiredMovies);
Also, I've noticed what seems to be an issue in the code that you've added, which might explain why you're getting all the movies.
In the code below, you're printing searchResult once for every successful result you're finding, which is an object which contains the count and the entire array items, so that'll show you all the movies in your data structure.
//searchResult is the object that contains the entire array "items"
searchResult.items.map(function(movie){
movie.scoring.filter(score =>{
if(score.provider_type ==="tmdb:score" && score.value > 8) {
//the variable searchResult has scope here so it will contain the entire list
print_result("search", searchResult)
}
})
})
Disclaimer: The following is meant only as constructive criticism.
Also, I'm fairly certain your usage of .map and .filter is incorrect. The callbacks supplied to these need to return a boolean value so that the .map or .filter functions themselves can return a new array (important to note that .map and .filter do not affect the original array). Not only do the callbacks supplied not return a boolean, the results of the map or filter themselves are not being stored in a variable. So, I suggest you take a look at the docs for these higher-order functions to get a better understanding of how they work:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Therefore I suggest you make a function that returns the filtered list of movies from the items list of your object and print that altogether.
As I understand, you want to filter Netflix shows with tmdb:score of 8 or greater right? So can we just use filter to filter the items?
searchResult.items.filter(function(movie){
var scorings = movie.scoring;
var filterScores =
scorings.filter(score => score.provider_type ==="tmdb:score" && score.value > 8);
return filterScores.length > 0;
})
const netflixId = 8
const searchResult = {
"items": [
{
"offers": [
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 8,
"currency": "USD",
"subtitle_languages": [
"en"
],
"presentation_type": "sd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
},
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 9,
"currency": "USD",
"subtitle_languages": [
"en"
],
"presentation_type": "hd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
}
],
"scoring": [
{
"provider_type": "imdb:score",
"value": 7.8
},
{
"provider_type": "tmdb:popularity",
"value": 3.422
},
{
"provider_type": "tmdb:score",
"value": 8.1
}
]
},
{
"offers": [
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 8,
"currency": "USD",
"subtitle_languages": [
"en"
],
"presentation_type": "sd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
},
{
"type": "aggregated",
"monetization_type": "flatrate",
"provider_id": 9,
"currency": "USD",
"subtitle_languages": [
"en"
],
"presentation_type": "hd",
"element_count": 1,
"new_element_count": 1,
"date_provider_id": "2019-09-14_9",
"date_created": "2019-09-14"
}
],
"scoring": [
{
"provider_type": "imdb:score",
"value": 7.8
},
{
"provider_type": "tmdb:popularity",
"value": 3.422
},
{
"provider_type": "tmdb:score",
"value": 7.9
}
]
}
]}
const movies = searchResult.items.filter(item => {
return item.offers.some(offer => offer.provider_id === netflixId) && item.scoring.some(score => score.provider_type === 'tmdb:score'&&score.value>=8)
})
console.log(movies)
const movies = searchResult.items.filter(item => {
return item.offers.some(offer => offer.provider_id === netflixId) && item.scoring.some(score => score.provider_type === 'tmdb:score'&&score.value>=8)
})
This filter function filter out item based on 2 conditions.
In item offers, one of offer needs to be from netflix
In item scoring, one of score needs to be tmdb:score and the score needs to be greater or equal than 8.
Hope it helps.

Need to get Name, Node Name and Phase Values from API

I am trying to get Name, Node Name and Phase values from JSON Data using JavaScript. Here is my JavaScript
<script>
$(document).ready(function () {
$.getJSON('http://ec2-3-82-117-70.compute-1.amazonaws.com:8080/api/v0/retrievePodStatus/default',
function (data) {
console.log(data)
document.body.append("Name: " + data.items[1].metadata.name);
// document.body.append(data.items[1].metadata.name);
// document.body.append(data.items[0].spec.nodeName);
});
});
</script>
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
"apiVersion": "v1",
"items": [
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}
],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [
{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}
],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
},
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
Thanks, Much Appreciated
You were close with the code you posted. You just needed items[0] instead of items[1]. Remember the first element of an array is always 0. Other than that its as easy as checking the open and close brackets [] or {} to see where each nested object/array starts and ends.
Code:
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
snippet:
var data = {
"apiVersion": "v1",
"items": [{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}]
}],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}]
},
"status": {
"conditions": [{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
}],
}
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
console.log(name)
console.log(nodeName)
console.log(phase)

Javascript: Loop through nested objects and arrays

I have an server response with data which has the structur as you can see in the codesnippet.
My goal is to iterate through each consent and add the channels
The data from the response:
[
{
"consents": [
{
"channels": [
{
"granted": true,
"id": "sms",
"title": "SMS/MMS"
},
{
"granted": true,
"id": "email",
"title": "E-Mail"
},
{
"granted": false,
"id": "phone",
"title": "Telefon"
},
{
"granted": false,
"id": "letter",
"title": "Brief"
}
],
"client": "App",
"configId": "99df8e86-2e24-4974-80da-74f901ba6a0d",
"date": "2018-03-08T16:03:25.753Z",
"granted": true,
"name": "bestandsdaten-alle-produkte",
"version": "1.0.0",
"versionId": "bd002dcd-fee6-42f8-aafe-22d0209a0646"
}
],
"createdAt": "2018-03-08T16:03:25.778Z",
"id": "1b9649a6-d8de-45c6-a0ae-a03cecf71cb5",
"updatedAt": "2018-03-08T16:03:25.778Z",
"username": "demo-app"
},
{
"consents": [
{
"channels": [
{
"granted": true,
"id": "sms",
"title": "SMS/MMS"
},
{
"granted": true,
"id": "email",
"title": "E-Mail"
},
{
"granted": true,
"id": "phone",
"title": "Telefon"
},
{
"granted": true,
"id": "letter",
"title": "Brief"
}
],
"client": "App",
"configId": "99df8e86-2e24-4974-80da-74f901ba6a0d",
"date": "2018-03-08T14:51:52.188Z",
"granted": true,
"name": "bestandsdaten-alle-produkte",
"version": "1.0.0",
"versionId": "bd002dcd-fee6-42f8-aafe-22d0209a0646"
}
],
"createdAt": "2018-03-08T14:51:52.208Z",
"id": "cf550425-990e-45ef-aaee-eced95d8fa08",
"updatedAt": "2018-03-08T14:51:52.208Z",
"username": "demo-app"
},
{
"consents": [
{
"channels": [
{
"granted": false,
"id": "sms",
"title": "SMS/MMS"
},
{
"granted": true,
"id": "email",
"title": "E-Mail"
},
{
"granted": true,
"id": "phone",
"title": "Telefon"
},
{
"granted": false,
"id": "letter",
"title": "Brief"
}
],
"client": "App",
"configId": "99df8e86-2e24-4974-80da-74f901ba6a0d",
"date": "2018-03-08T14:48:27.024Z",
"granted": true,
"name": "bestandsdaten-alle-produkte",
"version": "1.0.0",
"versionId": "bd002dcd-fee6-42f8-aafe-22d0209a0646"
}
],
"createdAt": "2018-03-08T14:48:27.054Z",
"id": "7fc1f087-2139-4494-bad7-161b0c6231a9",
"updatedAt": "2018-03-08T14:48:27.054Z",
"username": "demo-app"
},
]
The way i go is the following. But i need a way to append the channels to each Consent. Is there a way to solve this?
consentsList.forEach((consent, index, array) => {
consent.consents.forEach((c) => {
Object.keys(c).forEach((key) => {
dd.content.push(
{
columns: [
{
text: `${key}: `, style: 'text'
},
{
text: c[key], style: 'text'
}
]
}
);
});
});
Consents.push(consent);
if (index !== array.length - 1) {
dd.content.push({
margin: [0, 0, 0, 5],
canvas: [{
type: 'line', x1: 0, y1: 5, x2: 595 - (2 * 40), y2: 5, lineWidth: 0.6
}]
});
}
});
I want to output the individual channels where channels is on the top of each entry
You can extract the titles using map. And concantanate them using join like this.
let value = "";
if(key === "channels"){
value = c[key].map(x => x.title).join(" ,");
}
else {
value = c[key];
}
columns: [
{
text: `${key}: `, style: 'text'
},
{
text: value, style: 'text'
}
]
I have written a piece of code, hope this is what you're looking for. It is not optimized, try to optimize at your will
var a = responseData;
a.forEach(function(items) {
var allChannels = [];
items.consents.forEach(function(innerItems){
innerItems.channels.forEach(function(value){
allChannels.push(value.title);
})
items.allChannels = allChannels.join();
})
});
console.log(a);

Categories

Resources