Remove some values of object from json - javascript

I have this json-
"SkuList": [
{
"active": null,
"id": 698027,
"productSKUName": "v1",
"productSKUDescription": null,
"productSKUId": "02ffea0f-3d05-44"
},
{
"active": null,
"id": 698028,
"productSKUName": "v2",
"productSKUDescription": null,
"productSKUId": "628acbb9-0bdb-4ccf"
},
]
How do I filter this json and return this -
"brandProductSkuList": [
{
"id": 698027,
"productSKUId": "02ffea0f-3d05-4436",
},
{
"id": 698028,
"productSKUId": "628acbb9-0bdb-4ccf"
},
]
I want to remove certain properties of the object. How do I do this?

Yo can use map for this:
var SkuList = [
{
"active": null,
"id": 698027,
"productSKUName": "v1",
"productSKUDescription": null,
"productSKUId": "02ffea0f-3d05-44"
},
{
"active": null,
"id": 698028,
"productSKUName": "v2",
"productSKUDescription": null,
"productSKUId": "628acbb9-0bdb-4ccf"
},
];
var brandProductSkuList = SkuList.map((sku) => ({
id: sku.id,
productSkuId: sku.productSKUId
}));
console.log(brandProductSkuList);

Like this
var newObj=SkuList.map(x=>({id:x.id,productSKUId:x.productSKUId}))

var input = {"SkuList": [
{
"active": null,
"id": 698027,
"productSKUName": "v1",
"productSKUDescription": null,
"productSKUId": "02ffea0f-3d05-44"
},
{
"active": null,
"id": 698028,
"productSKUName": "v2",
"productSKUDescription": null,
"productSKUId": "628acbb9-0bdb-4ccf"
},
]
};
var output = input["SkuList"].map( o => (
{"id" : o["id"],"productSKUId" : o["productSKUId"] }
));
var outputObject = {
"brandProductSkuList": output
}
console.log(outputObject);

Recreate the array with Array#map() function
var arr = {"SkuList": [{ "active": null, "id": 698027,"productSKUName": "v1", "productSKUDescription": null, "productSKUId": "02ffea0f-3d05-44"},{"active": null,"id": 698028, "productSKUName": "v2","productSKUDescription": null, "productSKUId": "628acbb9-0bdb-4ccf"},]}
var res = {'brandProductSkuList':arr.SkuList.map(function(a){
return ({id:a['id'],productSKUName: a['productSKUName'],})
})}
console.log(res)

Related

Parse data from one format to another Typescript

I need to parse some data got from BE from one format to another to can inject it into a table component. The format received is:
{
"displayName": "Income",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4000 Revenue",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4100 Product 1 Revenue",
"baseVersionSum": -1000000,
"comparisonVersionSum": 4300000,
"variance": -5300000,
"variancePercent": -123,
"children": []
}
]
}
]
}
and I need the following format:
{
"key": "Income",
"data": {
"displayName": "Income",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null
},
"children": [
{
"key": "4000 Revenue",
"data": {
"displayName": "4000 Revenue",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null
},
"children": [
{
"key": "4100 Product 1 Revenue",
"data": {
"displayName": "4100 Product 1 Revenue",
"baseVersionSum": -1000000,
"comparisonVersionSum": 4300000,
"variance": -5300000,
"variancePercent": -123
},
"children": []
}
]
}
]
}
Each parent can have more children or no children.
I tried to do something with reduce, but no result. This is what I've tried:
const prepareTableValue = (data: any): any => {
const res = data.reduce((result: any, node) => {
if (node.children) {
result.push({
key: node.displayName,
data: {
displayName: node.displayName,
baseBersionSum: node.baseVersionSum,
comparisonVersionSum: node.comparisonVersionSum,
variance: node.variance,
variancePercent: node.variancePercent,
},
children: node.children,
});
prepareTableValue(node.children);
}
return result;
}, []);
return res;
};
Thanks in advance!
Nice challenge ! Here is a solution with a recursive function that creates a new object and adds to it recursively by going through each child of the initial object and calling itself for that child and the child in that position in the new object:
const objToFormat = {
"displayName": "Income",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4000 Revenue",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4100 Product 1 Revenue",
"baseVersionSum": -1000000,
"comparisonVersionSum": 4300000,
"variance": -5300000,
"variancePercent": -123,
"children": []
}
]
}
]
};
const formatData = (objToFormat, formattedObj = {}) => {
const { displayName, children, ...data } = objToFormat;
formattedObj.key = displayName;
formattedObj.data = { displayName, ...data };
formattedObj.children = [];
children.forEach((child, i) => {
formattedObj.children[i] = {};
formatData(child, formattedObj.children[i]);
})
return formattedObj;
}
console.log(formatData(objToFormat))
A recursive parse should work.
function parseData(items: any[]) {
const parsed = items.map((item) => {
const clone = Object.create(item);
clone.key = clone.displayName;
clone.data = {
displayName: clone.displayName,
baseBersionSum: clone.baseVersionSum,
comparisonVersionSum: clone.comparisonVersionSum,
variance: clone.variance,
variancePercent: clone.variancePercent,
};
clone.children = parseData(clone.children);
return clone;
});
return parsed;
}

Create new Array of object based on the Property Value

I want to create a new Array of objects based on Interface Value.
Like we need to group objects with the same Interface value. The new array would be like two new Objects with the same interface value. So here in the new generated array of objects, there would be two objects. Such as GE5 and GE6.I have a limitation to use only ES5.
There should be a looping logic
Logic
Loop through the data array. Which is the input.
Loop through cloudServices nodes in each node of the data and find the distict value.
Loop through this distinct values and and generate a group of each distict value using Array.filter.
Aggregate all the remainig values from each node in data array except the cloudServices node.
Generate a final object with this remaining values and the above generated group.
ES5 implementation
var data = [{ "id": 14042, "created": "2020-03-18T10:11:40.000Z", "enterpriseId": 437, "siteId": 6302, "activationKey": "PMZP-NGRU-HE64-SA5M", "activationKeyExpires": "2021-08-04T16:21:33.000Z", "activationState": "ACTIVATED", "activationTime": "2020-03-18T17:05:27.000Z", "softwareVersion": "4.3.0", "buildNumber": "R430-20210720-GA-64951-67694-6911a00421", "factorySoftwareVersion": "3.3.0", "factoryBuildNumber": "R330-MTHD-20190328-GA", "softwareUpdated": "2021-09-24T11:21:49.000Z", "selfMacAddress": "50:9a:4c:e4:1e:c0", "deviceId": "93AB7D33-87B7-42AA-BC0B-7D8255E069AD", "logicalId": "d25a6121-bf16-4512-b490-2dc5c45e11b8", "serialNumber": "F0TFXC2", "modelNumber": "edge610", "deviceFamily": "EDGE6X0", "name": "SDALM-BAYNARD-LAB-4", "dnsName": null, "description": "Dual Internet Site in Baynard", "alertsEnabled": 1, "operatorAlertsEnabled": 1, "edgeState": "CONNECTED", "edgeStateTime": "2021-09-24T11:23:00.000Z", "isLive": 0, "systemUpSince": "2021-09-24T11:20:55.000Z", "serviceUpSince": "2021-09-24T11:31:06.000Z", "lastContact": "2021-10-04T14:06:47.000Z", "serviceState": "IN_SERVICE", "endpointPkiMode": "CERTIFICATE_REQUIRED", "haState": "UNCONFIGURED", "haPreviousState": "UNCONFIGURED", "haLastContact": "0000-00-00 00:00:00", "haSerialNumber": null, "bastionState": "UNCONFIGURED", "modified": "2021-10-04T14:06:47.000Z", "customInfo": "", "isHub": false, "cloudServices": [{ "state": "UP", "timestamp": "2021-10-04T14:01:50.638Z", "link": "00000005-bf16-4512-b490-2dc5c45e11b8", "local_interface_ip": "172.16.2.1", "local_public_ip": "217.38.39.43", "nvs_ip": "165.225.16.236", "pathId": "211262ED9DE488A22CFEBBA9809092B32B937912", "segmentId": 0, "segmentLogicalId": "cd948075-e95f-4c7c-beb2-0fcde7e17c62", "l7_check": "UP", "l7_check_rtt": { "max": 11, "avg": 7, "min": 5 }, "site": { "id": 60282, "logicalId": "717f67c5-7426-4689-a74c-b58c93d4c3b1", "data": { "customSourceIp": "", "linkInternalLogicalId": "00000005-bf16-4512-b490-2dc5c45e11b8", "primaryAddressing": { "internalRouterIp": "172.22.60.145", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.146", "internalZenMask": "255.255.255.255" }, "secondaryAddressing": { "internalRouterIp": "172.22.60.149", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.150", "internalZenMask": "255.255.255.255" }, "useCustomSourceIp": false } }, "provider": { "name": "L7HC-LON3-MAN1-GRE", "id": 549697, "logicalId": "d5a058dc-6202-494c-b65d-6a8c273ed1c4", "data": { "primaryServer": "165.225.16.236", "secondaryServer": "165.225.196.39", "automateDeployment": false, "enableTunnels": true, "sharedIkeAuth": false, "maxTunnelsPerIkeIdentity": 128, "l7HealthCheck": { "enabled": true, "probeIntervalSec": 5, "numOfRetries": 3, "rttThresholdMs": 3000, "cloud": "zscloud.net" }, "provider": "zscalerWebSecurityService" } }, "segmentName": "Global Segment", "interface": "GE5" }, { "state": "STANDBY", "timestamp": "2021-10-04T14:01:50.638Z", "link": "00000005-bf16-4512-b490-2dc5c45e11b8", "local_interface_ip": "172.16.2.1", "local_public_ip": "217.38.39.43", "nvs_ip": "165.225.196.39", "pathId": "26434D16946CFD147D5DDFA50647F48A0066AB31", "segmentId": 0, "segmentLogicalId": "cd948075-e95f-4c7c-beb2-0fcde7e17c62", "l7_check": "UP", "l7_check_rtt": { "max": 10, "avg": 6, "min": 5 }, "site": { "id": 60282, "logicalId": "717f67c5-7426-4689-a74c-b58c93d4c3b1", "data": { "customSourceIp": "", "linkInternalLogicalId": "00000005-bf16-4512-b490-2dc5c45e11b8", "primaryAddressing": { "internalRouterIp": "172.22.60.145", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.146", "internalZenMask": "255.255.255.255" }, "secondaryAddressing": { "internalRouterIp": "172.22.60.149", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.150", "internalZenMask": "255.255.255.255" }, "useCustomSourceIp": false } }, "provider": { "name": "L7HC-LON3-MAN1-GRE", "id": 549697, "logicalId": "d5a058dc-6202-494c-b65d-6a8c273ed1c4", "data": { "primaryServer": "165.225.16.236", "secondaryServer": "165.225.196.39", "automateDeployment": false, "enableTunnels": true, "sharedIkeAuth": false, "maxTunnelsPerIkeIdentity": 128, "l7HealthCheck": { "enabled": true, "probeIntervalSec": 5, "numOfRetries": 3, "rttThresholdMs": 3000, "cloud": "zscloud.net" }, "provider": "zscalerWebSecurityService" } }, "segmentName": "Global Segment", "interface": "GE5" }, { "state": "STANDBY", "timestamp": "2021-10-04T14:01:50.638Z", "link": "00000006-bf16-4512-b490-2dc5c45e11b8", "local_interface_ip": "172.16.1.1", "local_public_ip": "217.38.39.41", "nvs_ip": "165.225.196.39", "pathId": "9B88047C891952D8A661F30A8E7C0A5842AB8544", "segmentId": 0, "segmentLogicalId": "cd948075-e95f-4c7c-beb2-0fcde7e17c62", "l7_check": "UP", "l7_check_rtt": { "max": 16, "avg": 6, "min": 5 }, "site": { "id": 60282, "logicalId": "717f67c5-7426-4689-a74c-b58c93d4c3b1", "data": { "customSourceIp": "", "linkInternalLogicalId": "00000005-bf16-4512-b490-2dc5c45e11b8", "primaryAddressing": { "internalRouterIp": "172.22.60.145", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.146", "internalZenMask": "255.255.255.255" }, "secondaryAddressing": { "internalRouterIp": "172.22.60.149", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.150", "internalZenMask": "255.255.255.255" }, "useCustomSourceIp": false } }, "provider": { "name": "L7HC-LON3-MAN1-GRE", "id": 549697, "logicalId": "d5a058dc-6202-494c-b65d-6a8c273ed1c4", "data": { "primaryServer": "165.225.16.236", "secondaryServer": "165.225.196.39", "automateDeployment": false, "enableTunnels": true, "sharedIkeAuth": false, "maxTunnelsPerIkeIdentity": 128, "l7HealthCheck": { "enabled": true, "probeIntervalSec": 5, "numOfRetries": 3, "rttThresholdMs": 3000, "cloud": "zscloud.net" }, "provider": "zscalerWebSecurityService" } }, "segmentName": "Global Segment", "interface": "GE6" }, { "state": "UP", "timestamp": "2021-10-04T14:01:50.638Z", "link": "00000006-bf16-4512-b490-2dc5c45e11b8", "local_interface_ip": "172.16.1.1", "local_public_ip": "217.38.39.41", "nvs_ip": "165.225.16.236", "pathId": "DB965CA91A564DE09027F8D766F92CD0DDB54405", "segmentId": 0, "segmentLogicalId": "cd948075-e95f-4c7c-beb2-0fcde7e17c62", "l7_check": "UP", "l7_check_rtt": { "max": 1063, "avg": 41, "min": 5 }, "site": { "id": 60282, "logicalId": "717f67c5-7426-4689-a74c-b58c93d4c3b1", "data": { "customSourceIp": "", "linkInternalLogicalId": "00000005-bf16-4512-b490-2dc5c45e11b8", "primaryAddressing": { "internalRouterIp": "172.22.60.145", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.146", "internalZenMask": "255.255.255.255" }, "secondaryAddressing": { "internalRouterIp": "172.22.60.149", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.150", "internalZenMask": "255.255.255.255" }, "useCustomSourceIp": false } }, "provider": { "name": "L7HC-LON3-MAN1-GRE", "id": 549697, "logicalId": "d5a058dc-6202-494c-b65d-6a8c273ed1c4", "data": { "primaryServer": "165.225.16.236", "secondaryServer": "165.225.196.39", "automateDeployment": false, "enableTunnels": true, "sharedIkeAuth": false, "maxTunnelsPerIkeIdentity": 128, "l7HealthCheck": { "enabled": true, "probeIntervalSec": 5, "numOfRetries": 3, "rttThresholdMs": 3000, "cloud": "zscloud.net" }, "provider": "zscalerWebSecurityService" } }, "segmentName": "Global Segment", "interface": "GE6" }] }];
//Function to find distinct valies of an object array with specific key
function distinct(dataArray, key) {
var distinctList = [];
dataArray.forEach(function (node) {
if (distinctList.indexOf(node[key]) === -1) {
distinctList.push(node[key]);
}
});
return distinctList;
}
// Reference https://stackoverflow.com/a/34710102/6099327
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) {
continue;
}
if (!Object.prototype.hasOwnProperty.call(obj, i)) {
continue;
}
target[i] = obj[i];
}
return target;
}
var parsedOutput = [];
data.forEach(function (dataNode) {
var distinctInterfaces = distinct(dataNode.cloudServices, "interface");
var remainingProperties = _objectWithoutProperties(dataNode, ["cloudServices"]);
var output = remainingProperties;
distinctInterfaces.forEach(function (interface) {
output[interface] = dataNode.cloudServices.filter(function (node) {
return node.interface === interface;
});
});
parsedOutput.push(output);
});
console.log(parsedOutput);
ES6 Implementation will be a little more easy
const data = [{"id":14042,"created":"2020-03-18T10:11:40.000Z","enterpriseId":437,"siteId":6302,"activationKey":"PMZP-NGRU-HE64-SA5M","activationKeyExpires":"2021-08-04T16:21:33.000Z","activationState":"ACTIVATED","activationTime":"2020-03-18T17:05:27.000Z","softwareVersion":"4.3.0","buildNumber":"R430-20210720-GA-64951-67694-6911a00421","factorySoftwareVersion":"3.3.0","factoryBuildNumber":"R330-MTHD-20190328-GA","softwareUpdated":"2021-09-24T11:21:49.000Z","selfMacAddress":"50:9a:4c:e4:1e:c0","deviceId":"93AB7D33-87B7-42AA-BC0B-7D8255E069AD","logicalId":"d25a6121-bf16-4512-b490-2dc5c45e11b8","serialNumber":"F0TFXC2","modelNumber":"edge610","deviceFamily":"EDGE6X0","name":"SDALM-BAYNARD-LAB-4","dnsName":null,"description":"Dual Internet Site in Baynard","alertsEnabled":1,"operatorAlertsEnabled":1,"edgeState":"CONNECTED","edgeStateTime":"2021-09-24T11:23:00.000Z","isLive":0,"systemUpSince":"2021-09-24T11:20:55.000Z","serviceUpSince":"2021-09-24T11:31:06.000Z","lastContact":"2021-10-04T14:06:47.000Z","serviceState":"IN_SERVICE","endpointPkiMode":"CERTIFICATE_REQUIRED","haState":"UNCONFIGURED","haPreviousState":"UNCONFIGURED","haLastContact":"0000-00-00 00:00:00","haSerialNumber":null,"bastionState":"UNCONFIGURED","modified":"2021-10-04T14:06:47.000Z","customInfo":"","isHub":false,"cloudServices":[{"state":"UP","timestamp":"2021-10-04T14:01:50.638Z","link":"00000005-bf16-4512-b490-2dc5c45e11b8","local_interface_ip":"172.16.2.1","local_public_ip":"217.38.39.43","nvs_ip":"165.225.16.236","pathId":"211262ED9DE488A22CFEBBA9809092B32B937912","segmentId":0,"segmentLogicalId":"cd948075-e95f-4c7c-beb2-0fcde7e17c62","l7_check":"UP","l7_check_rtt":{"max":11,"avg":7,"min":5},"site":{"id":60282,"logicalId":"717f67c5-7426-4689-a74c-b58c93d4c3b1","data":{"customSourceIp":"","linkInternalLogicalId":"00000005-bf16-4512-b490-2dc5c45e11b8","primaryAddressing":{"internalRouterIp":"172.22.60.145","internalRouterMask":"255.255.255.255","internalZenIp":"172.22.60.146","internalZenMask":"255.255.255.255"},"secondaryAddressing":{"internalRouterIp":"172.22.60.149","internalRouterMask":"255.255.255.255","internalZenIp":"172.22.60.150","internalZenMask":"255.255.255.255"},"useCustomSourceIp":false}},"provider":{"name":"L7HC-LON3-MAN1-GRE","id":549697,"logicalId":"d5a058dc-6202-494c-b65d-6a8c273ed1c4","data":{"primaryServer":"165.225.16.236","secondaryServer":"165.225.196.39","automateDeployment":false,"enableTunnels":true,"sharedIkeAuth":false,"maxTunnelsPerIkeIdentity":128,"l7HealthCheck":{"enabled":true,"probeIntervalSec":5,"numOfRetries":3,"rttThresholdMs":3000,"cloud":"zscloud.net"},"provider":"zscalerWebSecurityService"}},"segmentName":"Global Segment","interface":"GE5"},{"state":"STANDBY","timestamp":"2021-10-04T14:01:50.638Z","link":"00000005-bf16-4512-b490-2dc5c45e11b8","local_interface_ip":"172.16.2.1","local_public_ip":"217.38.39.43","nvs_ip":"165.225.196.39","pathId":"26434D16946CFD147D5DDFA50647F48A0066AB31","segmentId":0,"segmentLogicalId":"cd948075-e95f-4c7c-beb2-0fcde7e17c62","l7_check":"UP","l7_check_rtt":{"max":10,"avg":6,"min":5},"site":{"id":60282,"logicalId":"717f67c5-7426-4689-a74c-b58c93d4c3b1","data":{"customSourceIp":"","linkInternalLogicalId":"00000005-bf16-4512-b490-2dc5c45e11b8","primaryAddressing":{"internalRouterIp":"172.22.60.145","internalRouterMask":"255.255.255.255","internalZenIp":"172.22.60.146","internalZenMask":"255.255.255.255"},"secondaryAddressing":{"internalRouterIp":"172.22.60.149","internalRouterMask":"255.255.255.255","internalZenIp":"172.22.60.150","internalZenMask":"255.255.255.255"},"useCustomSourceIp":false}},"provider":{"name":"L7HC-LON3-MAN1-GRE","id":549697,"logicalId":"d5a058dc-6202-494c-b65d-6a8c273ed1c4","data":{"primaryServer":"165.225.16.236","secondaryServer":"165.225.196.39","automateDeployment":false,"enableTunnels":true,"sharedIkeAuth":false,"maxTunnelsPerIkeIdentity":128,"l7HealthCheck":{"enabled":true,"probeIntervalSec":5,"numOfRetries":3,"rttThresholdMs":3000,"cloud":"zscloud.net"},"provider":"zscalerWebSecurityService"}},"segmentName":"Global Segment","interface":"GE5"},{"state":"STANDBY","timestamp":"2021-10-04T14:01:50.638Z","link":"00000006-bf16-4512-b490-2dc5c45e11b8","local_interface_ip":"172.16.1.1","local_public_ip":"217.38.39.41","nvs_ip":"165.225.196.39","pathId":"9B88047C891952D8A661F30A8E7C0A5842AB8544","segmentId":0,"segmentLogicalId":"cd948075-e95f-4c7c-beb2-0fcde7e17c62","l7_check":"UP","l7_check_rtt":{"max":16,"avg":6,"min":5},"site":{"id":60282,"logicalId":"717f67c5-7426-4689-a74c-b58c93d4c3b1","data":{"customSourceIp":"","linkInternalLogicalId":"00000005-bf16-4512-b490-2dc5c45e11b8","primaryAddressing":{"internalRouterIp":"172.22.60.145","internalRouterMask":"255.255.255.255","internalZenIp":"172.22.60.146","internalZenMask":"255.255.255.255"},"secondaryAddressing":{"internalRouterIp":"172.22.60.149","internalRouterMask":"255.255.255.255","internalZenIp":"172.22.60.150","internalZenMask":"255.255.255.255"},"useCustomSourceIp":false}},"provider":{"name":"L7HC-LON3-MAN1-GRE","id":549697,"logicalId":"d5a058dc-6202-494c-b65d-6a8c273ed1c4","data":{"primaryServer":"165.225.16.236","secondaryServer":"165.225.196.39","automateDeployment":false,"enableTunnels":true,"sharedIkeAuth":false,"maxTunnelsPerIkeIdentity":128,"l7HealthCheck":{"enabled":true,"probeIntervalSec":5,"numOfRetries":3,"rttThresholdMs":3000,"cloud":"zscloud.net"},"provider":"zscalerWebSecurityService"}},"segmentName":"Global Segment","interface":"GE6"},{"state":"UP","timestamp":"2021-10-04T14:01:50.638Z","link":"00000006-bf16-4512-b490-2dc5c45e11b8","local_interface_ip":"172.16.1.1","local_public_ip":"217.38.39.41","nvs_ip":"165.225.16.236","pathId":"DB965CA91A564DE09027F8D766F92CD0DDB54405","segmentId":0,"segmentLogicalId":"cd948075-e95f-4c7c-beb2-0fcde7e17c62","l7_check":"UP","l7_check_rtt":{"max":1063,"avg":41,"min":5},"site":{"id":60282,"logicalId":"717f67c5-7426-4689-a74c-b58c93d4c3b1","data":{"customSourceIp":"","linkInternalLogicalId":"00000005-bf16-4512-b490-2dc5c45e11b8","primaryAddressing":{"internalRouterIp":"172.22.60.145","internalRouterMask":"255.255.255.255","internalZenIp":"172.22.60.146","internalZenMask":"255.255.255.255"},"secondaryAddressing":{"internalRouterIp":"172.22.60.149","internalRouterMask":"255.255.255.255","internalZenIp":"172.22.60.150","internalZenMask":"255.255.255.255"},"useCustomSourceIp":false}},"provider":{"name":"L7HC-LON3-MAN1-GRE","id":549697,"logicalId":"d5a058dc-6202-494c-b65d-6a8c273ed1c4","data":{"primaryServer":"165.225.16.236","secondaryServer":"165.225.196.39","automateDeployment":false,"enableTunnels":true,"sharedIkeAuth":false,"maxTunnelsPerIkeIdentity":128,"l7HealthCheck":{"enabled":true,"probeIntervalSec":5,"numOfRetries":3,"rttThresholdMs":3000,"cloud":"zscloud.net"},"provider":"zscalerWebSecurityService"}},"segmentName":"Global Segment","interface":"GE6"}]}];
const parsedOutput = data.map((node) => {
const { cloudServices, ...otherNodes } = node;
const uniqueInterfaces = [ ...new Set(cloudServices.map(service => service.interface)) ];
interfaceObj = uniqueInterfaces.reduce((acc, curr) => {
acc[curr] = cloudServices.filter((node) => node.interface === curr);
return acc;
}, {})
return { ...otherNodes, ...interfaceObj };
});
console.log(parsedOutput)

Find a key value based on a match in Javascript

I'm trying to return the uuid where the urns key has this match.
"urns": [
"whatsapp:27820111111"
],
What should be returned d7b9f88c-b359-4d69-926d-536c0d2892e0 since it has that phone number match. How can this be done programmatically.
Here's are the two dicts.
{
"next": "https://random.com=",
"previous": null,
"results": [
{
"uuid": "g2ws8dh5-b359-4d69-926d-536c0d2892e0",
"name": "James",
"language": "eng",
"urns": [
"whatsapp:27333333333"
],
"groups": [
{
"uuid": "57fs8430-3c78-42b7-876c-c385e36c1dba",
"name": "Postbirth WhatsApp"
}
],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
},
{
"uuid": "d7b9f88c-b359-4d69-926d-536c0d2892e0",
"name": "Jane",
"language": "eng",
"urns": [
"whatsapp:27820111111"
],
"groups": [
{
"uuid": "e35f2e39-3c78-42b7-876c-c385e36c1dba",
"name": "Prebirth WhatsApp"
}
],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
}
]
}
I'm able to loop through and find the urn but I'm not sure how to step back to get the uuid.
Pass in the results array and the urn string to this function. If found it will return the uuid, else it will return null.
function getIdFromUrn(results, urn) {
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result.urns.includes(urn)) {
return result.uuid; // urn found
}
}
return null; // not found
}
console.log(getIdFromUrn(results, 'whatsapp:27820111111'));
You don't need to loop when you can use find(...) to match against a value.
See demo below
var data = [{
"uuid": "g2ws8dh5-b359-4d69-926d-536c0d2892e0",
"name": "James",
"language": "eng",
"urns": [
"whatsapp:27333333333"
],
"groups": [{
"uuid": "57fs8430-3c78-42b7-876c-c385e36c1dba",
"name": "Postbirth WhatsApp"
}],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
},
{
"uuid": "d7b9f88c-b359-4d69-926d-536c0d2892e0",
"name": "Jane",
"language": "eng",
"urns": [
"whatsapp:27820111111"
],
"groups": [{
"uuid": "e35f2e39-3c78-42b7-876c-c385e36c1dba",
"name": "Prebirth WhatsApp"
}],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
}
];
const lookingFor = "whatsapp:27820111111";
const foundIt = data.find(el => {
return (el.urns.indexOf(lookingFor) !== -1);
});
console.log(foundIt.uuid);

Nesting a parent child relationship in lodash, given the parent id and children

How would I be able to nest json object if the parent and its children was given as a property.
The data looks like:
"1": {
"id": 1,
"name": "foo",
"parent": null,
"root": 1,
"children": [2, 4, 6],
"posts":[
{ "id": "1", "name": "item1" },
{ "id": "2", "name": "item2" },
{ "id": "3", "name": "item3" }
]
},
"2": {
"id": 2,
"name": "bar",
"parent": 1,
"root": 1,
"children": null,
"posts":[
{ "id": "4", "name": "item4" }
]
},
"3": {
"id": 3,
"name": "bazz",
"parent": null,
"root": 3,
"children": [5, 7],
"posts":[
{ "id": "5", "name": "item5" },
{ "id": "6", "name": "item6" }
]
},
....
A simple groupby using lodash won't do it.
var group = _.groupBy(data, 'parent');
Here is a fiddle:
http://jsfiddle.net/tzugzo8a/1/
The context of question is a nested categories with subcategories, and categories can have categories and posts in them.
Basically I don't want to have a different property for children and posts, since they are all children of a parent.
Desired output
"1": {
"id": 1,
"name": "foo",
"parent": null,
"root": 1,
"isCategory": true,
"children": [
{
"id": 2,
"name": "bar",
"parent": 1,
"root": 1,
"isCategory": true,
"children": null
},
{ "id": "1", "name": "item1", isCategory: false },
{ "id": "2", "name": "item2", isCategory: false },
{ "id": "3", "name": "item3", isCategory: false }
]
...
}
This is my take on the question (fiddle):
var data = getData();
var group = getTree(data);
console.log(group);
function getTree(flat) {
return _.reduce(flat, function (treeObj, item, prop, flatTree) {
var children = _.map(item.children, function (childId) {
return _.set(flatTree[childId], 'isCategory', true);
}).concat(_.map(item.items, function(item) {
return _.set(item, 'isCategory', false);
}));
item.children = !!children.length ? children : null;
delete item.items;
item.parent === null && (treeObj[prop] = item);
return treeObj;
}, {});
}
Take a look on the updated fiddle:
var data = getData();
_.keys(data).forEach(function(id){
var element = data[id];
if (element.children === null){
element.children = [];
}
element.isCategory = true;
element.items.forEach(function(item){
item.isCategory = false;
})
});
_.keys(data).forEach(function(id){
var element = data[id];
element.children = element.children.map(function(childId){
return data[childId];
}).concat(element.items);
});
_.keys(data).forEach(function(id){
delete data[id].items;
});
console.log(JSON.stringify(_.findWhere(_.values(data), {'parent': null})));

Getting a variable from a multidimentional JSON array using Jquery

I am retrieving a multidimensional JSON array using JQUERY.
I need to print out various items from the array, but am having a hard time figuring out how to go through the array and get these items so I can insert them into the HTML.
Here is an example of the array (this is what is taken from the jsonpage.php referenced below.
{
"count":1,
"total_count":1,
"contacts":[
{
"id":92840643,
"user_id":55536,
"first_name":"John",
"last_name":"Doe",
"full_name":"John Doe",
"initials":"JD",
"title":null,
"company":null,
"email":"john#doe.com",
"avatar":"https://graph.facebook.com/123454/picture?type=large",
"avatar_url":"https://graph.facebook.com/123454/picture?type=large",
"last_contacted":null,
"visible":true,
"twitter":null,
"facebook_url":null,
"linkedin_url":null,
"first_contacted":null,
"created_at":"2014-05-26T19:06:55Z",
"updated_at":"2014-05-26T19:12:42Z",
"hits":0,
"user_bucket_id":486405,
"team_parent_id":null,
"snoozed_at":null,
"snooze_days":null,
"groupings":[
{
"id":21554286,
"type":"Grouping::Location",
"name":"Johnson, NY",
"stub":"frisco tx",
"bucket_id":null,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null
},
{
"id":21553660,
"type":"Grouping::Bucket",
"name":"Top Customers",
"stub":"top customers",
"bucket_id":486405,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null,
"has_followups":true,
"num_days_to_followup":30,
"program_id":null
}
],
"email_addresses":[
"john#doe.com"
],
"tags":[
],
"contact_status":3,
"team_last_contacted":null,
"team_last_contacted_by":null,
"phone_numbers":[
],
"addresses":[
{
"_id":"538390cfcc0fb067d8000353",
"created_at":"2014-05-26T19:06:55Z",
"deleted_at":null,
"extra_data":{
"address_city":"Johnson",
"address_state":"NY",
"address_country":"United States"
},
"label":"Address",
"primary":null,
"remote_id":null,
"updated_at":"2014-05-26T19:06:55Z",
"username":null,
"value":"Johnson, NY\nUnited States"
}
],
"social_profiles":[
],
"websites":[
],
"custom_fields":[
{
"_id":"538390cfcc0fb067d8000354",
"custom_field_id":46639,
"deleted_at":null,
"label":"WeeklyNews",
"value":"YES"
},
{
"_id":"538390cfcc0fb067d8000355",
"custom_field_id":46640,
"deleted_at":null,
"label":"Current Credits",
"value":"142"
},
{
"_id":"538390cfcc0fb067d8000356",
"custom_field_id":46641,
"deleted_at":null,
"label":"Total Purchased Amount",
"value":"400"
},
{
"_id":"538390cfcc0fb067d8000357",
"custom_field_id":46642,
"deleted_at":null,
"label":"VDownloads",
"value":"112"
},
{
"_id":"538390cfcc0fb067d8000358",
"custom_field_id":46643,
"deleted_at":null,
"label":"AEDownloads",
"value":"9"
},
{
"_id":"538390cfcc0fb067d8000359",
"custom_field_id":46644,
"deleted_at":null,
"label":"ADownloads",
"value":"53"
},
{
"_id":"538390cfcc0fb067d800035a",
"custom_field_id":46638,
"deleted_at":null,
"label":"Last Login",
"value":"2014-05-25 23:14:19"
},
{
"_id":"538390cfcc0fb067d800035b",
"custom_field_id":46649,
"deleted_at":null,
"label":"Label",
"value":"Group1"
}
]
}
]
}
And here is the jquery success code:
$.post('/jsonpage.php', post_data, function(response) {
});
Now, if I put alert(response); within the function i.e.:
$.post('/jsonpage.php', post_data, function(response) {
alert(response);
});
Then, it 'does' alert the entire JSON string as listed above.
However, if I put this:
$.post('/jsonpage.php', post_data, function(response) {
alert(response.count);
});
Then, I get UNDEFINED in the alert box. I have tried a few different variables to 'alert' and they all come back undefined.
Thanks for your help!
Craig
response.total_count
response.contacts[0].id
response.contacts[0].groupings[0].stub
And so on.
Here are some ways of using the data in your json response. Hope it helps.
$.post('/jsonpage.php', post_data, function(response) {
if (!response.contacts || !response.contacts.length) {
alert("Error loading that/those contact(s)");
return;
}
for (var i=0, c; c = response.contacts[i]; i++) {
// c is each contact, do stuff with c
alert("That contact was created at " + c.created_at + " and last updated at " + c.updated_at);
var cities = [];
for (var j=0, a; a = c.addresses[j]; j++) {
// a refers to each address
cities.push(a.extra_data.address_city);
}
alert(c.full_name + " lives in " + cities.join(" and ") + ".");
for (var j=0, cf; cf = c.custom_fields[j]; j++) {
// cf is each custom_field
// build a form or something
// element label is cf.label
// element value is currently cf.value
var p = document.createElement("p");
p.appendChild(document.createTextNode(cf.label));
var el = document.createElement("input");
el.type = "text";
el.value = cf.value;
p.appendChild(el);
document.getElementById("someForm").appendChild(p);
}
}
});
Try this
var data = { "count": 1, "total_count": 1, "contacts": [{ "id": 92840643, "user_id": 55536, "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "initials": "JD", "title": null, "company": null, "email": "john#doe.com", "avatar": "https://graph.facebook.com/123454/picture?type=large", "avatar_url": "https://graph.facebook.com/123454/picture?type=large", "last_contacted": null, "visible": true, "twitter": null, "facebook_url": null, "linkedin_url": null, "first_contacted": null, "created_at": "2014-05-26T19:06:55Z", "updated_at": "2014-05-26T19:12:42Z", "hits": 0, "user_bucket_id": 486405, "team_parent_id": null, "snoozed_at": null, "snooze_days": null, "groupings": [{ "id": 21554286, "type": "Grouping::Location", "name": "Johnson, NY", "stub": "frisco tx", "bucket_id": null, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null }, { "id": 21553660, "type": "Grouping::Bucket", "name": "Top Customers", "stub": "top customers", "bucket_id": 486405, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null, "has_followups": true, "num_days_to_followup": 30, "program_id": null}], "email_addresses": ["john#doe.com"], "tags": [], "contact_status": 3, "team_last_contacted": null, "team_last_contacted_by": null, "phone_numbers": [], "addresses": [{ "_id": "538390cfcc0fb067d8000353", "created_at": "2014-05-26T19:06:55Z", "deleted_at": null, "extra_data": { "address_city": "Johnson", "address_state": "NY", "address_country": "United States" }, "label": "Address", "primary": null, "remote_id": null, "updated_at": "2014-05-26T19:06:55Z", "username": null, "value": "Johnson, NY\nUnited States"}], "social_profiles": [], "websites": [], "custom_fields": [{ "_id": "538390cfcc0fb067d8000354", "custom_field_id": 46639, "deleted_at": null, "label": "WeeklyNews", "value": "YES" }, { "_id": "538390cfcc0fb067d8000355", "custom_field_id": 46640, "deleted_at": null, "label": "Current Credits", "value": "142" }, { "_id": "538390cfcc0fb067d8000356", "custom_field_id": 46641, "deleted_at": null, "label": "Total Purchased Amount", "value": "400" }, { "_id": "538390cfcc0fb067d8000357", "custom_field_id": 46642, "deleted_at": null, "label": "VDownloads", "value": "112" }, { "_id": "538390cfcc0fb067d8000358", "custom_field_id": 46643, "deleted_at": null, "label": "AEDownloads", "value": "9" }, { "_id": "538390cfcc0fb067d8000359", "custom_field_id": 46644, "deleted_at": null, "label": "ADownloads", "value": "53" }, { "_id": "538390cfcc0fb067d800035a", "custom_field_id": 46638, "deleted_at": null, "label": "Last Login", "value": "2014-05-25 23:14:19" }, { "_id": "538390cfcc0fb067d800035b", "custom_field_id": 46649, "deleted_at": null, "label": "Label", "value": "Group1"}]}] };
alert(data["contacts"][0]["id"]);
//get count
alert(data["count"]); //1
//get first contacts data
data["contacts"][0]["id"] //retruns 92840643
//do same for others to get data

Categories

Resources