I have a flat object structure which outlines which objects have parents and which don't. I'm now at the point that I need it to be formatted in the correct structure so I can loop through it and perform functions.
Just to add before I go into detail.. I know the Object structure is not consistent, I'm still working on making sure all individual items are consistent. The most important part is that children are aligned with parents.
I've searched online, but couldn't seem to find anything that fit my exact need. The structure, whether good or bad, is what I'm stuck with now.
I was fiddling with this code which does loop and append children to the appropriate parent, and removes the old key. I forgot about recursion and can't wrap my head around doing this... in this specific case.
var tree = hierarchy.tree, key;
for (key in tree) {
if (tree.hasOwnProperty(key)) tree[key].children = {};
}
iterate();
return tree;
function iterate() {
var field, node;
for (field in tree) {
if (tree.hasOwnProperty(field)) {
node = tree[field];
if (node.parent !== undefined) {
tree[node.parent].children[field] = node;
delete tree[field];
}
}
}
}
This is the base structure:
var tree = {
"submit": {
"order": 0,
"field": "submit"
},
"hc3qu2nf4": {
"label": "title",
"parent": "",
"order": 0,
"field": "title",
"options": {
"Font Size": "25px",
"Font Weight": "Bold",
"Font Style": "Italic",
"Color": "rgb(64, 128, 128)"
}
},
"dhthivju9": {
"label": "divider",
"parent": "",
"order": 1,
"field": "divider",
"options": {
"height": "14px",
"color": "#21ce09",
"width": "50%"
}
},
"z5o9m7sgx": {
"label": "",
"parent": "4hhsi94n7",
"order": 0,
"field": "col"
},
"85ugwci2c": {
"label": "",
"parent": "4hhsi94n7",
"order": 1,
"field": "col"
},
"4hhsi94n7": {
"label": "column",
"parent": "",
"order": 2,
"field": "column"
},
"sbf0bg1o7": {
"label": "month",
"parent": "z5o9m7sgx",
"order": 0,
"field": "month",
"options": {
"start": "2019-04"
},
"required": true
},
"c3bwnyjmg": {
"label": "",
"parent": "4hhsi94n7",
"order": 2
},
"n5m9d84dg": {
"label": "number",
"parent": "85ugwci2c",
"order": 0,
"field": "number",
"options": {
"start": "5",
"min": "5",
"max": "10",
"step": "2"
}
},
"krfxfnzsr": {
"label": "date",
"parent": "c3bwnyjmg",
"order": 0,
"field": "date",
"options": {
"start": "2019-05-03"
}
}
}
Ideally I would like the structure to be like this below. There could be multiple more layers than this.
{
"submit": {
"order": 0,
"field": "submit"
},
"hc3qu2nf4": {
"label": "title",
"parent": "",
"order": 0,
"field": "title",
"options": {
"Font Size": "25px",
"Font Weight": "Bold",
"Font Style": "Italic",
"Color": "rgb(64, 128, 128)"
}
},
"dhthivju9": {
"label": "divider",
"parent": "",
"order": 1,
"field": "divider",
"options": {
"height": "14px",
"color": "#21ce09",
"width": "50%"
}
},
"4hhsi94n7": {
"label": "column",
"parent": "",
"order": 2,
"field": "column",
"children": {
"z5o9m7sgx": {
"label": "",
"order": 0,
"field": "col",
"children": {
"sbf0bg1o7": {
"label": "month",
"parent": "z5o9m7sgx",
"order": 0,
"field": "month",
"options": {
"start": "2019-04"
},
"required": true
}
}
},
"85ugwci2c": {
"label": "",
"order": 1,
"field": "col",
"children": {
"n5m9d84dg": {
"label": "number",
"parent": "85ugwci2c",
"order": 0,
"field": "number",
"options": {
"start": "5",
"min": "5",
"max": "10",
"step": "2"
}
}
}
},
"c3bwnyjmg": {
"label": "",
"order": 2,
"children": {
"krfxfnzsr": {
"label": "date",
"parent": "c3bwnyjmg",
"order": 0,
"field": "date",
"options": {
"start": "2019-05-03"
}
}
}
}
}
}
}
In addition, it could be great if I could maintain the appropriate "order" of each item, so they are sorted appropriately.
UPDATE
I'm not married to the output structure. If someone has a better idea please let me know.
I found this solution but it uses arrays instead of objects (for find, reduce, splice, push, etc...) so the final output is not exactly what you wanted, but you wrote it was not set in stone.
const data = {
"submit": {
"order": 0,
"field": "submit"
},
"hc3qu2nf4": {
"label": "title",
"parent": "",
"order": 0,
"field": "title",
"options": {
"Font Size": "25px",
"Font Weight": "Bold",
"Font Style": "Italic",
"Color": "rgb(64, 128, 128)"
}
},
"dhthivju9": {
"label": "divider",
"parent": "",
"order": 1,
"field": "divider",
"options": {
"height": "14px",
"color": "#21ce09",
"width": "50%"
}
},
"z5o9m7sgx": {
"label": "",
"parent": "4hhsi94n7",
"order": 0,
"field": "col"
},
"85ugwci2c": {
"label": "",
"parent": "4hhsi94n7",
"order": 1,
"field": "col"
},
"4hhsi94n7": {
"label": "column",
"parent": "",
"order": 2,
"field": "column"
},
"sbf0bg1o7": {
"label": "month",
"parent": "z5o9m7sgx",
"order": 0,
"field": "month",
"options": {
"start": "2019-04"
},
"required": true
},
"c3bwnyjmg": {
"label": "",
"parent": "4hhsi94n7",
"order": 2
},
"n5m9d84dg": {
"label": "number",
"parent": "85ugwci2c",
"order": 0,
"field": "number",
"options": {
"start": "5",
"min": "5",
"max": "10",
"step": "2"
}
},
"krfxfnzsr": {
"label": "date",
"parent": "c3bwnyjmg",
"order": 0,
"field": "date",
"options": {
"start": "2019-05-03"
}
}
};
function sortArray(orderedArray, remainingArray) {
if(remainingArray.length === 0) {
return orderedArray;
}
else {
remainingArray.forEach((remainingItem, index) => {
if(orderedArray.find(x => x.identifier === remainingItem.parent)) {
orderedArray.push(remainingItem);
remainingArray.splice(index, 1);
}
});
return sortArray(orderedArray, remainingArray);
}
}
function insertNode(tree, node) {
if(!tree) return;
let item = tree.find(x => x.identifier === node.parent);
if(item) {
(item.children || (item.children = [])).push(node);
} else {
tree.forEach(x => {
insertNode(x.children, node);
});
}
return tree;
}
function createTree(data) {
let tempArray = [];
for (let key in data) {
tempArray.push({ ...data[key], identifier: key });
}
tempArray = sortArray(tempArray.filter(x => !x.parent), tempArray.filter(x => x.parent));
return tempArray.reduce((accumulator, currentValue) => {
if(currentValue.parent === "") {
accumulator.push(currentValue);
} else {
insertNode(accumulator, currentValue);
}
return accumulator;
}, []);
}
console.log(createTree(data));
The example below preserves Object type instead of switching to Array. See inline comments for more details. Basic concept is to treat the tree itself as a master branch and iterate through branches until finding the parent to reposition the child to.
//iterating through an object/array that's changing can cause unexpected results
//iterate through a duplicate that will not change
let tree = {
"submit": {
"order": 0,
"field": "submit"
},
"hc3qu2nf4": {
"label": "title",
"parent": "",
"order": 0,
"field": "title",
"options": {
"Font Size": "25px",
"Font Weight": "Bold",
"Font Style": "Italic",
"Color": "rgb(64, 128, 128)"
}
},
"dhthivju9": {
"label": "divider",
"parent": "",
"order": 1,
"field": "divider",
"options": {
"height": "14px",
"color": "#21ce09",
"width": "50%"
}
},
"z5o9m7sgx": {
"label": "",
"parent": "4hhsi94n7",
"order": 0,
"field": "col"
},
"85ugwci2c": {
"label": "",
"parent": "4hhsi94n7",
"order": 1,
"field": "col"
},
"4hhsi94n7": {
"label": "column",
"parent": "",
"order": 2,
"field": "column"
},
"sbf0bg1o7": {
"label": "month",
"parent": "z5o9m7sgx",
"order": 0,
"field": "month",
"options": {
"start": "2019-04"
},
"required": true
},
"c3bwnyjmg": {
"label": "",
"parent": "4hhsi94n7",
"order": 2
},
"n5m9d84dg": {
"label": "number",
"parent": "85ugwci2c",
"order": 0,
"field": "number",
"options": {
"start": "5",
"min": "5",
"max": "10",
"step": "2"
}
},
"krfxfnzsr": {
"label": "date",
"parent": "c3bwnyjmg",
"order": 0,
"field": "date",
"options": {
"start": "2019-05-03"
}
}
},
tree2 = JSON.parse(JSON.stringify(tree)); //clone, not reference
console.log(tree === tree2); //test to confirm duplicate is not a reference
function reposition_child(parent, child, node, branch) {
//check if the parent exists in this branch
if (branch.hasOwnProperty(parent)) {
let bp = branch[parent];
//create children object as needed
if (!bp.hasOwnProperty('children')) {
bp.children = {};
}
//transplant the node as a child
bp.children[child] = node;
return true;
} else {
//iterate through the branches with children looking for the parent
let found = false;
for (let sub_branch in branch) {
if (branch[sub_branch].hasOwnProperty('children')) {
found = reposition_child(parent, child, node, branch[sub_branch].children);
}
//exit the loop once the parent is found
if (found) {
return true;
}
}
}
return false;
}
//iterate through the tree (duplicate fixed version)
for (let node in tree2) {
let tn = tree2[node];
//reposition nodes that have a non-empty parent
if (tn.hasOwnProperty('parent') && tn.parent.length) {
reposition_child(tn.parent, node, tn, tree);
delete tree[node];
}
}
//cleanup and output
delete tree2;
console.log(tree);
Related
Hi I have below code running, but I would like to add one more property called path which should consist all its parent node path
Expected output I need something as I have shown for cardTtile, so I need same for each node.
[
{
"id": "cardShop",
"key": "cardShop",
"title": "cardShop",
"selectable": false,
"path":cardShop"
"children": [
{
"id": "cardData",
"key": "cardData",
"title": "cardData",
"parentId": "cardShop",
"path":cardShop.cardData"
"selectable": false,
"children": [
{
"id": "cardTitle",
"key": "cardTitle",
"title": "cardTitle",
"parentId": "cardData",
"path":cardShop.cardData.cardTitle"
"isLeaf": true
},
{
"id": "cardType",
"key": "cardType",
"title": "cardType",
"parentId": "cardData",
"isLeaf": true
},
{
"id": "dtmProductName",
"key": "dtmProductName",
"title": "dtmProductName",
"parentId": "cardData",
"isLeaf": true
},
{
"id": "viewAllCards",
"key": "viewAllCards",
"title": "viewAllCards",
"parentId": "cardData",
"selectable": false,
"children": [
{
"id": "url",
"key": "url",
"title": "url",
"parentId": "viewAllCards",
"isLeaf": true
},
{
"id": "text",
"key": "text",
"title": "text",
"parentId": "viewAllCards",
"isLeaf": true
}
]
}
]
},
{
"id": "eligibilityChecker",
"key": "eligibilityChecker",
"title": "eligibilityChecker",
"parentId": "cardShop",
"selectable": false,
"children": [
{
"id": "header",
"key": "header",
"title": "header",
"parentId": "eligibilityChecker",
"isLeaf": true
},
{
"id": "subHeader",
"key": "subHeader",
"title": "subHeader",
"parentId": "eligibilityChecker",
"isLeaf": true
},
{
"id": "bulletPoints",
"key": "bulletPoints",
"title": "bulletPoints",
"parentId": "eligibilityChecker",
"isLeaf": true
}
]
}
]
}
]
I have below running code example here. I tried to persist parentKey recursively but its not giving me expected output.
const transform = data => {
const loop = (data, parent) => Object.entries(data).map(([key, value]) => {
let additional = parent? {
parentId: parent
}:{}
if(typeof value === 'object' && !Array.isArray(value)){
additional = {
...additional,
selectable: false,
children: loop(value, key)
}
}else{
additional.isLeaf = true
}
return {
id: key,
key,
title: key,
...additional
}
})
return loop(data)
}
let jsonObj = {
"data": {
"cardShop": {
"cardData": {
"cardTitle": "The Platinum Card<sup>®</sup>",
"cardType": "credit-cards",
"dtmProductName": "PlatinumCard",
"viewAllCards": {
"url": "credit-cards/all-cards",
"text": "All Cards"
}
},
"eligibilityChecker": {
"header": "Check your eligibility",
"subHeader": "The Platinum Card®",
"bulletPoints": [
"Only takes a couple of minutes to complete",
"Will not impact your credit rating",
"Allows you to apply with confidence"
]
}
}
}
}
console.log(transform(jsonObj.data))
]
You suggestion would be appreciated
Thanks
You could take another variable for path and add the actual key to it.
const transform = data => {
const loop = (data, parentId, previousPath = '') => Object
.entries(data)
.map(([key, value]) => {
const
additional = parentId ? { parentId } : {},
path = previousPath + (previousPath && '.') + key;
Object.assign(
additional,
value && typeof value === 'object' && !Array.isArray(value)
? { selectable: false, children: loop(value, key, path) }
: { isLeaf: true }
);
return { id: key, key, title: key, path, ...additional };
});
return loop(data);
}
const data = { cardShop: { cardData: { cardTitle: "The Platinum Card<sup>®</sup>", cardType: "credit-cards", dtmProductName: "PlatinumCard", viewAllCards: { url: "credit-cards/all-cards", text: "All Cards" } }, eligibilityChecker: { header: "Check your eligibility", subHeader: "The Platinum Card®", bulletPoints: ["Only takes a couple of minutes to complete", "Will not impact your credit rating", "Allows you to apply with confidence"] } } };
console.log(transform(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
So I have two tables in my database. I want a DataGrid UI to print all my columns except the categoryId I want to print a label instead (like in selection valueOptions) :
const columns: GridColDef = [
{
"field": "title",
"headerName": "Titel",
"width": 350,
"editable": true
},
{
"field": "categoryId",
"headerName": "Kategorie",
"width": 250,
"editable": true,
"type": "singleSelect",
"valueOptions": [
{
"value": "miv560972ynqzk9",
"label": "stuff 1"
},
{
"value": "1t7n08l9tfdwotn",
"label": "stuff 2"
},
]
}
]
const rows: GridRowsProp = [
{
"categoryId": "miv560972ynqzk9",
"title": "Lineare Algebra Hausaufga",
},
{
"categoryId": "1t7n08l9tfdwotn",
"title": "Test",
},
]
So I want something like this:
const rows: GridRowsProp = [
{
"categoryId": { value:"miv560972ynqzk9", label: "stuff1"},
"title": "Lineare Algebra Hausaufga",
},
{
"categoryId": { value: "1t7n08l9tfdwotn", label: "stuff2" },
"title": "Test",
},
]
I have a react components that needs to dynamically preload some values from a couple of arrays in the background from a couple of nested objects in 1 array of data.
import React, {
useEffect
} from "react";
export function layoutComponent({
config,
LayoutRenderer
}) {
const loadModules = (name) => queryModule(name);
useEffect(() => {
const modules = parseModules(config);
modules.forEach(module => loadModules(module));
}, [])
return ( <
LayoutRenderer config = {
modules
}
/>
)
}
layoutComponent.propTypes = {
LayoutRenderer: PropTypes.node.isRequired,
config: PropTypes.shape({}).isRequired,
}
I need to take the parseModules and create a function that parse through the array of objects below called config. I need to get the name value from config.header.customizableArea.slots.modules.name and I need to also get overview.slots.modules.name
config = [{
"name": "Default",
"description": "This is the default layout configuration.",
"userGroup": "gg-servicing-wings-ccp",
"header": {
"accountEnabled": true,
"ucidEnabled": true,
"journeySearchEnabled": true,
"customizableArea": {
"className": "",
"height": "",
"slots": [{
"slotId": "00",
"layout": "",
"visibleModule": "servicing-card-art",
"className": "dls-white-bg",
"size": {
"sm": {
"rowSpan": "1",
"colSpan": "6"
},
"md": {
"rowSpan": "1",
"colSpan": "6"
},
"lg": {
"rowSpan": "1",
"colSpan": "6"
}
},
"modules": [{
"name": "servicing-card-art",
"props": ["accountToken", "accountToken:accountTokenToDisplay"]
}]
},
{
"slotId": "01",
"layout": "",
"visibleModule": "servicing-card-art",
"className": "dls-white-bg",
"size": {
"sm": {
"rowSpan": "1",
"colSpan": "6"
},
"md": {
"rowSpan": "1",
"colSpan": "6"
},
"lg": {
"rowSpan": "1",
"colSpan": "6"
}
},
"modules": [{
"name": "servicing-card-art",
"props": ["accountToken", "accountToken:accountTokenToDisplay"]
}]
}
]
}
},
"overview": {
"className": "",
"height": "",
"slots": [{
"slotId": "00",
"layout": "",
"visibleModule": "servicing-card-art",
"className": "dls-white-bg",
"size": {
"sm": {
"rowSpan": "1",
"colSpan": "2"
},
"md": {
"rowSpan": "1",
"colSpan": "2"
},
"lg": {
"rowSpan": "1",
"colSpan": "2"
}
},
"modules": [{
"name": "servicing-card-art",
"props": ["accountToken", "accountToken:accountTokenToDisplay"]
}]
},
{
"slotId": "01",
"layout": "",
"visibleModule": "servicing-card-art",
"className": "dls-white-bg",
"size": {
"sm": {
"rowSpan": "1",
"colSpan": "2"
},
"md": {
"rowSpan": "1",
"colSpan": "2"
},
"lg": {
"rowSpan": "1",
"colSpan": "2"
}
},
"modules": [{
"name": "servicing-card-art",
"props": ["accountToken", "accountToken:accountTokenToDisplay"]
}]
},
{
"slotId": "02",
"layout": "",
"visibleModule": "servicing-card-art",
"className": "dls-white-bg",
"size": {
"sm": {
"rowSpan": "1",
"colSpan": "2"
},
"md": {
"rowSpan": "1",
"colSpan": "2"
},
"lg": {
"rowSpan": "1",
"colSpan": "2"
}
},
"modules": [{
"name": "servicing-card-art",
"props": ["accountToken", "accountToken:accountTokenToDisplay"]
}]
}
]
},
"autoLaunch": ["servicing-card-replacement"]
}]
The below works for me to generate a list with the name fields from your sample data, although they are the same module name, so not sure if you needed something else there as well...
const parseModules = (config) => {
const modules = [];
// Loop over objects in config.header
config.forEach(conf => {
conf.header.customizableArea.slots.forEach(slot => {
slot.modules.forEach(module => modules.push(module.name))
})
});
// Loop over objects in config.overview
config.forEach(conf => {
conf.overview.slots.forEach(slot => {
slot.modules.forEach(module => modules.push(module.name))
})
});
return modules;
}
const modules = parseModules(config);
Result: ["servicing-card-art", "servicing-card-art", "servicing-card-art", "servicing-card-art", "servicing-card-art"]
I have the following nested object and I need to leave the "alias" property blank and the "group" property set to true for all "entries" and "exits". I also need to delete the whole "parameters" object.
Would there be a way to do it all in one function? I've tried to apply the delete Object method but it doesn't work as it's an indexed object.
{
"1": {
"x": 114,
"y": 135,
"properties": {
"id": 1,
"entries": {
"entry_0": {
"id": 1,
"alias": "do",
"group": false
}
},
"exits": {
"exit_0": {
"id": 1,
"alias": "re",
"group": false
}
},
"parameters": {
"parameter_0": {
"id": 3,
"group": false
}
},
"order": 1
}
},
"2": {
"x": 700,
"y": 104,
"properties": {
"id": 1
"entries": {
"entry_0": {
"id": 1
"alias": "do"
"group": false
}
},
"exits": {
"exyt_0": {
"id": 1
"alias": "re"
"group": false
}
},
"parameters": {
"parameter_0": {
"id": 3
"alias": "mi"
"group": false
}
},
"order": 2
}
}
}
the desired nested object would be the following
{
"1": {
"x": 114,
"y": 135,
"properties": {
"id": 1,
"entries": {
"entry_0": {
"id": 1,
"alias": "",
"group": true
}
},
"exits": {
"exit_0": {
"id": 1,
"alias": "",
"group": true
}
},
"order": 1
}
},
"2": {
"x": 700,
"y": 104,
"properties": {
"id": 1
"entries": {
"entry_0": {
"id": 1
"alias": ""
"group": true
}
},
"exits": {
"exyt_0": {
"id": 1
"alias": ""
"group": true
}
},
"order": 2
}
}
}
what I've tried is the following, managing to delete the "parameters" object but I can't access the "label" property of each "entry" and "exit
const nedtedObjectsValues = Object.values(nestedObjects);
for (object of nedtedObjectsValues) {
delete object.properties.parameters;
}
if anyone can give me an idea of how to approach this function.
Thank you in advance.
In JavaScript, to reference numeric object properties, you need to use the square brackets syntax:
object.1 // bad
object[1] // good
You can delete numeric property like this:
delete object[1];
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)