Looping through items in an object for google sheets - javascript

I am trying to loop through an array that is part of a JSON object from a page speed insights call to add all of the unused javascript Urls to a google sheet using the script editor.
Here is an example of the JSON object:
"audits": {
"unused-javascript": {
"id": "unused-javascript",
"title": "Remove unused JavaScript",
"description": "Remove unused JavaScript to reduce bytes consumed by network activity. [Learn more](https://web.dev/unused-javascript/).",
"score": 0.43,
"scoreDisplayMode": "numeric",
"numericValue": 1350,
"numericUnit": "millisecond",
"displayValue": "Potential savings of 231 KiB",
"details": {
"type": "opportunity",
"headings": [
{
"key": "url",
"valueType": "url",
"subItemsHeading": {
"key": "source",
"valueType": "code"
},
"label": "URL"
},
{
"key": "totalBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceBytes"
},
"label": "Transfer Size"
},
{
"key": "wastedBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceWastedBytes"
},
"label": "Potential Savings"
}
],
"items": [
{
"url": "https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable",
"totalBytes": 140229,
"wastedBytes": 108197,
"wastedPercent": 77.15757011763822
},
{
"url": "https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js",
"totalBytes": 306716,
"wastedBytes": 106243,
"wastedPercent": 34.63892414884589
},
{
"url": "https://www.googletagmanager.com/gtm.js?id=GTM-KZ",
"totalBytes": 127214,
"wastedBytes": 21845,
"wastedPercent": 17.17151000374831
}
],
"overallSavingsMs": 1350,
"overallSavingsBytes": 236285
}
},
I am attempting to loop through the "items" array within the "unused-javascript" object and get all of the urls to show in google sheets.
Here is the code I have within the script editor. When I run this, only one URL shows on the sheet. However, I am trying to get all of the URLs added to the sheet.
function pageSpeed(Url) {
var key = "AIzaSyAyHY";
var serviceUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + Url + "&key=" + key;
var array = [];
if (key == "YOUR_API_KEY")
return "Please enter your API key to the script";
var response = UrlFetchApp.fetch(serviceUrl);
if (response.getResponseCode() == 200) {
var content = JSON.parse(response.getContentText());
if ((content != null) && (content["lighthouseResult"] != null)) {
if (content["captchaResult"]) {
var timetointeractive = content["lighthouseResult"]["audits"]["interactive"]["displayValue"].slice(0, -2);
var firstcontentfulpaint = content["lighthouseResult"]["audits"]["first-contentful-paint"]["displayValue"].slice(0, -2);
var firstmeaningfulpaint = content["lighthouseResult"]["audits"]["first-meaningful-paint"]["displayValue"].slice(0, -2);
var speedindex = content["lighthouseResult"]["audits"]["speed-index"]["displayValue"].slice(0, -2);
var unusedJs = content["lighthouseResult"]["audits"]["unused-javascript"]["details"]["items"];
for (var i = 0; i < unusedJs.items.length; i++) {
var unusedUrl;
unusedUrl = unusedJs[i]["url"]
}
}
else {
var timetointeractive = "An error occured";
var firstcontentfulpaint = "An error occured";
var firstmeaningfulpaint = "An error occured";
var speedindex = "An error occured";
var unusedJs = "An error occured";
}
}
var currentDate = new Date().toJSON().slice(0, 10).replace(/-/g, '/');
array.push([timetointeractive, firstcontentfulpaint, firstmeaningfulpaint, speedindex, currentDate, "complete", unusedUrl]);
Utilities.sleep(1000);
return array;
}
}
Any and all help is appreciated!

You're on the right track.
Take a look below at my usage of Array.prototype.map. That's the simpler route.
Your for loop would work just as well IF you declared unusedUrl outside of (ie. before) the loop AND pushed to an existing array. As it is, there's an issue of scope, so unusedUrl is redeclared on every iteration, meaning you'll only assign the last iteration's value to unusedUrl.
Both solutions are below.
Using map
var content = {
lighthouseResult: {
audits: {
'unused-javascript': {
// Other stuff
details: {
// Other stuff
items: [
{
url:
'https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable',
totalBytes: 140229,
wastedBytes: 108197,
wastedPercent: 77.15757011763822,
},
{
url:
'https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js',
totalBytes: 306716,
wastedBytes: 106243,
wastedPercent: 34.63892414884589,
},
{
url: 'https://www.googletagmanager.com/gtm.js?id=GTM-KZ',
totalBytes: 127214,
wastedBytes: 21845,
wastedPercent: 17.17151000374831,
},
],
overallSavingsMs: 1350,
overallSavingsBytes: 236285,
},
},
},
},
}
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = items.map(item => item.url) // OR, using es6, items.map(({ url }) => url)
console.log(unusedUrls)
Using for
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = []
for (var i = 0; i < items.length; i++) {
unusedUrls.push(items[i]['url'])
}

Related

Parsing JSON into Google spreadsheet (Apps Script)

I have a download in JSON format that I get through the API.
Example:
{
"Employees": [
{
"User": {
"UserId": "4d132227-ea5c-4e57-b105-2f8b97872545",
"Login": "test#gmail.com",
"FullName": {
"LastName": "Фамилия",
"FirstName": "Имя",
"MiddleName": "Отчество"
},
"IsRegistered": true
},
"Permissions": {
"UserDepartmentId": "b5072e57-1e96-490b-ae03-2fd52ef84a3a",
"IsAdministrator": false,
"DocumentAccessLevel": "SelectedDepartments",
"SelectedDepartmentIds": [
"b5072e57-1e96-490b-ae03-2fd52ef84a3a",
"cd2e04dc-8d3f-4d63-88fd-f900c496e146",
"36e4434b-519d-4e40-9253-3464c10ed83e"
],
"Actions": [
{
"Name": "CreateDocuments",
"IsAllowed": true
},
{
"Name": "DeleteRestoreDocuments",
"IsAllowed": true
},
{
"Name": "SignDocuments",
"IsAllowed": true
},
{
"Name": "AddResolutions",
"IsAllowed": true
},
{
"Name": "RequestResolutions",
"IsAllowed": true
},
{
"Name": "ManageCounteragents",
"IsAllowed": false
}
],
"AuthorizationPermission": {
"IsBlocked": false
}
},
"Position": "Специалист по снабжению",
"CanBeInvitedForChat": true,
"CreationTimestamp": {
"Ticks": 637284074150000000
}
}
],
"TotalCount": 214
}
An example of what should happen:
enter image description here
The ratio of the JSON list of employees with columns in the table:
A: "User": {"UserId"} - Employee ID
B: "User": {""FullName""} - FULL NAME
C: "Position" - Position
D: "User": {"Login"} - Mail
E: "User": {"IsRegistered"} - Login activated?
F: "Permissions": {"IsAdministrator"} - Administrator?
G: "Permissions": {"Actions": [{"Name": "SignDocuments","isAllowed": true} - Can sign documents
H: "Permissions": {"Actions": [{"Name": "AddResolutions","isAllowed": true} - Can coordinate documents
I: "Permissions": {"Actions": [{"Name": "RequestResolutions","isAllowed": true} - Can request document approval
J: "Permissions": {"Actions": [{"Name": "CreateDocuments","isAllowed": true} - Can create documents and work with drafts
K: "Permissions": {"Actions": [{"Name": "DeleteRestoreDocuments","isAllowed": true} - Can delete documents and drafts, restore documents
L: "Permissions": {"Actions": [{"Name": "ManageCounteragents","isAllowed": true} - Can work with a list of counterparties
How can I convert JSON to a Google spreadsheet for 300+ rows? At the moment I only have a request to the API. The response is JSON. What are my next steps?
function GetEmployees(){
var DdocAuthKey = GetAuthToken()
for (let i = 0; i < boxId.length; i++) {
let url = `https://diadoc-api.kontur.ru/GetEmployees?boxId=`+ boxId[i]
let options =
{
method: "GET",
contentType: 'application/json',
headers: {authorization: "DiadocAuth ddauth_api_client_id=" + DdocAPIkey + `,ddauth_token=` + DdocAuthKey}
}
var json = UrlFetchApp.fetch(url, options)
var obj = JSON.parse(json)
printValues(obj);enter code here
}
}
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
return obj[k] + "<br>"
}
}
}
This is the final version of the code. I hope this will help developers on JS and Apps Script when working with the Diadoc API.
Due to the fact that I have 3 organizations, I need to do an additional cycle:
for (let i = 0; i < boxId.length; i++)
If necessary, this cycle can be removed.
function GetEmployees() {
clearOrgSheets()
var DdocAuthKey = GetAuthToken()
let options =
{
method: "GET",
contentType: 'application/json',
headers: {authorization: "DiadocAuth ddauth_api_client_id=" + DdocAPIkey + `,ddauth_token=` + DdocAuthKey}
}
for (let i = 0; i < boxId.length; i++) {
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SheetNames[i])
let pageNum = 1
do {
let url = `https://diadoc-api.kontur.ru/GetEmployees?boxId=`+ boxId[i] + `&page=` + pageNum + `&count=50`
pageNum++
var obj = JSON.parse(UrlFetchApp.fetch(url, options))
var table = []; // it will be the 2d array
for (var employee of obj.Employees) {
var {LastName, FirstName, MiddleName} = employee.User.FullName;
var name = [LastName, FirstName, MiddleName].join(' ').trim();
var actions = {};
employee.Permissions.Actions.forEach(a => actions[a.Name] = a.IsAllowed);
var row =
[
employee.User.UserId,
name,
employee.Position,
employee.User.Login,
employee.User.IsRegistered,
employee.Permissions.IsAdministrator,
actions.SignDocuments, // Can sign documents
actions.AddResolutions, // Can coordinate documents
actions.RequestResolutions, // Can request document approval
actions.CreateDocuments, // Can create documents and work with drafts
actions.DeleteRestoreDocuments, // Can delete documents and drafts, restore documents
actions.ManageCounteragents, // Can work with a list of counterparties
];
table.push(row);
}
let lastRow = sheet.getLastRow() + 1
try{
let range = sheet.getRange(lastRow, 1, table.length, table[0].length )
range.setValues(table);
} catch (err){
break
}
} while (obj.Employees.length > 0);
}
}
Try this:
function myFunction() {
// here is your object (parsed json)
var obj = {
"Employees": [
{
"User": {
"UserId": "4d132227-ea5c-4e57-b105-2f8b97872545",
"Login": "test#gmail.com",
"FullName": {
"LastName": "Фамилия",
"FirstName": "Имя",
"MiddleName": "Отчество"
},
"IsRegistered": true
},
"Permissions": {
"UserDepartmentId": "b5072e57-1e96-490b-ae03-2fd52ef84a3a",
"IsAdministrator": false,
"DocumentAccessLevel": "SelectedDepartments",
"SelectedDepartmentIds": [ "b5072e57", "cd2e04dc", "36e4434b" ],
"Actions": [
{ "Name": "CreateDocuments", "IsAllowed": true },
{ "Name": "DeleteRestoreDocuments", "IsAllowed": true },
{ "Name": "SignDocuments", "IsAllowed": true },
{ "Name": "AddResolutions", "IsAllowed": true },
{ "Name": "RequestResolutions", "IsAllowed": true },
{ "Name": "ManageCounteragents", "IsAllowed": false }
],
"AuthorizationPermission": { "IsBlocked": false }
},
"Position": "Специалист по снабжению",
"CanBeInvitedForChat": true,
"CreationTimestamp": { "Ticks": 637284074150000000 }
}
],
"TotalCount": 214
};
var table = []; // it will be the 2d array
for (var employee of obj.Employees) {
var {LastName, FirstName, MiddleName} = employee.User.FullName;
var name = [LastName, FirstName, MiddleName].join(' ');
var actions = {};
employee.Permissions.Actions.forEach(a => actions[a.Name] = a.IsAllowed);
var row = [
employee.User.UserId,
name,
employee.Position,
employee.User.Login,
employee.User.IsRegistered,
employee.Permissions.IsAdministrator,
actions.SignDocuments, // Can sign documents
actions.AddResolutions, // Can coordinate documents
actions.RequestResolutions, // Can request document approval
actions.CreateDocuments, // Can create documents and work with drafts
actions.DeleteRestoreDocuments, // Can delete documents and drafts, restore documents
actions.ManageCounteragents, // Can work with a list of counterparties
];
table.push(row); // add the row to the 2d array
}
// put the 2d array on the sheet
SpreadsheetApp.getActiveSheet()
.getRange(2,1,table.length,table[0].length)
.setValues(table);
}
Let me know if it works.

How to add external data to javascript for jquery auto complete

I'm trying to make a auto complete search bar using jquery autocomplete. The thing is I need to display Json data from an external site into my search bar.
Whenever I try to put the data as such from json into the script, it's working. But when I refer external url it refuses to work.
I tried implementing all json data into my script. But it takes so long to process as there will be more than 40000+ lines in my html page.
The Json link for the data which I have to display is here
<script>
$('#id_ticker').autocomplete({
source: function(request, response) {
var data = {
"success": true,
"data": [
{
"symbol": "AACG",
"name": "ATA Creativity Global American Depositary Shares",
"lastsale": "$2.19",
"netchange": "-0.45",
"pctchange": "-17.045%",
"volume": "1408435",
"marketCap": "68715455.00",
"country": "China",
"ipoyear": "",
"industry": "Service to the Health Industry",
"sector": "Miscellaneous",
"url": "/market-activity/stocks/aacg"
},
{
"symbol": "AACI",
"name": "Armada Acquisition Corp. I Common Stock",
"lastsale": "$9.88",
"netchange": "0.01",
"pctchange": "0.101%",
"volume": "8345",
"marketCap": "204609860.00",
"country": "United States",
"ipoyear": "2021",
"industry": "",
"sector": "",
"url": "/market-activity/stocks/aaci"
}],
"additional_data": {
"pagination": {
"start": 0,
"limit": 5,
"more_items_in_collection": true,
"next_start": 5
}
}
};
var datamap = data.data.map(function(i) {
return {
label: i.symbol + ' - ' + i.name.split(' ').slice(0, 2).join(' '),
value: i.symbol,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
});
response(datamap);
},
minLength: 1,
delay: 500
});
</script>
The above code works and the below code doesn't.
<script>
$('#id_ticker').autocomplete({
source: function(request, response) {
var data = {
"success": true,
"data": ["https://raw.githubusercontent.com/rreichel3/US-Stock-Symbols/main/nyse/nyse_full_tickers.json"
],
"additional_data": {
"pagination": {
"start": 0,
"limit": 5,
"more_items_in_collection": true,
"next_start": 5
}
}
};
var datamap = data.data.map(function(i) {
return {
label: i.symbol + ' - ' + i.name.split(' ').slice(0, 2).join(' '),
value: i.symbol,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
});
response(datamap);
},
minLength: 1,
delay: 500
});
</script>
Looking for a solution to add this and also for a solution to reduce the json key pair with only "symbol" and "name" from each corresponding data in the link.
Try this:
function toAutocomplete(dt, keyvar){
let rli = [];
for (let i = 0; i < dt.length; i++) rli.push(dt[i][keyvar]);
return rli;
}
function inArrayAutocompleteSelected(key, array_autocomplete, array_master){
let x = array_master[$.inArray(key, array_autocomplete)];
return x;
}
$('#id_ticker').autocomplete({ source: [], minLength: 1 });
// $('#id_ticker').autocomplete("disable");
let url = 'https://raw.githubusercontent.com/rreichel3/US-Stock-Symbols/main/nyse/nyse_full_tickers.json';
let r = _ajax('GET', url, ''); // your ajax script
console.log(r);
let liAuto = toAutocomplete(r, 'name');
console.log(liAuto);
$('#id_ticker').autocomplete("option", "source", liAuto );
// $('#id_ticker').autocomplete("enable");
$("#id_ticker").autocomplete({
select: function( event, ui ) {
console.log(ui, ui.item);
getData = inArrayAutocompleteSelected(ui.item.value, liAuto, r);
console.log(getData);
}
});

How to process multidimensional array from jQuery Sortable (nested list)?

I'm working with jQuery Sortable to create some block of codes with nested list ( for loop and function block), then I got this json string use JSON.stringify on console.log(jsonString):
{
"codes": [
[
{
"id": "code_run",
"code": "run",
"name": "code_when_run"
},
{
"id": "",
"code": "loop",
"name": "code_block_repeat",
"children": [
[
{
"id": "",
"code": "up",
"name": "code_arrow_up"
},
{
"id": "",
"code": "up",
"name": "code_arrow_up"
}
]
]
}
]
]
}
Here's my code from the jQuery sortable's example :
let oldContainer, codeBlockId, codeBlockItem;
$("ol.nest_workspace").sortable({
group: 'nested',
onDragStart: function ($item, container, _super) {
// Duplicate items of the no drop area
if(!container.options.drop)
$item.clone().insertAfter($item);
_super($item, container);
},
afterMove: function (placeholder, container) {
if(oldContainer != container){
if(oldContainer)
oldContainer.el.removeClass("active");
container.el.addClass("active");
oldContainer = container;
}
},
onDrop: function ($item, container, _super) {
container.el.removeClass("active");
$item.addClass("block_code_on_workspace");
var data = group.sortable("serialize").get();
var jsonString = JSON.stringify({"codes":data}, null, '\t');
console.log(jsonString);
_super($item, container);
},
});
How can I process the sub array (children[]) ?
I have plan to make it all block as a real codes, so it could execute with another function.
I may expect the text output printed some function like moveUp(), or if its loop with some function inside, then would be like :
for (var i = 0; i < 3; i++) {
moveUp();
}
Any help or suggest would be great, thanks!
If your JSON string will always look like this. Then you can target there “children" array like this.
I wrote this code base only on the format of the JSON that you have above.
const childrenArr = jsonString.codes[0][1].children;
Based on the code we’re you are stringifying your data this code should work.
var jsonString = JSON.stringify({"codes":data}, null, '\t');
console.log(jsonString),
ChildrenArr = jsonString.codes[0][1].children;
I've found a solution for my problem, here's the code :
$("ol.nest_workspace").sortable({
group: 'nested',
onDragStart: function ($item, container, _super) {
// Duplicate items of the no drop area
if(!container.options.drop)
$item.clone().insertAfter($item);
if($item.hasClass('RepeatCode')){
$item.attr('id','block_loop_function_drag');
}
_super($item, container);
},
afterMove: function (placeholder, container) {
if(oldContainer != container){
if(oldContainer)
oldContainer.el.removeClass("active");
container.el.addClass("active");
oldContainer = container;
}
},
onDrop: function ($item, container, _super) {
$(".coding-script").empty();
container.el.removeClass("active");
$item.addClass("block_code_on_workspace");
$hasID = document.getElementById('block_loop_function_drag');
var data = group.sortable("serialize").get();
// console.log(data);
for(var i = 0; i < data[0].length; i++){
if($hasID){
$item.attr('id','block_loop_function_'+i+'');
}
var obj = data[0][i];
if(obj.hasOwnProperty("children")){
var objChildren = obj.children[0];
console.log(obj.code +'-'+i);
ConvertToCodeScripts(obj.code, i);
for(var j = 0; j < objChildren.length; j++){
console.log('loop-'+i+'-'+objChildren[j].code);
ConvertToCodeScripts('loop-'+i+'-'+objChildren[j].code, i);
}
}
else{
console.log(obj.code);
ConvertToCodeScripts(obj.code, i);
}
console.log('lha - '+i);
}
_super($item, container);
},
});
But let me know if you guys have a better solution.
Cheers

Nested Pointer Data

I'm calling the below Parse Query using the Parse Server Javascript API. I have a class called Device, which has a pointer object to Device_Type which in turn has a pointer to Manufacturer.
I can successfully display the deviceID in inventoryItem, but get undefined for manufacturer, despite there being the relevant data in the JSON network return.
$scope.getDeviceItems = function () {
var query = new Parse.Query("Device");
query.include("Device_Type");
query.include("Device_Type.Manufacturer");
query.find({
success: function (results) {
$scope.deviceItems = [];
for (i = 0; i < results.length; i++) {
var d = results[i].get("Device_Type");
var m = results[i].get("Device_Type.Manufacturer");
var inventoryItem = {
deviceID: d.get("Device_ID"),
manufacturer: m.get("Manufacturer_Name")
}
};
};
};
};
How would I correctly obtain the nested pointer data into manufacturer?
Here's a sample JSON Object:
{
"results": [{
"objectId": "q3D2myHG3e",
"createdAt": "2017-07-30T22:28:05.035Z",
"updatedAt": "2017-09-19T20:40:05.580Z",
"Device_Type": {
"objectId": "Ksej3F2sdp5",
"Device_Name": "Device 1",
"createdAt": "2017-07-30T21:57:58.638Z",
"updatedAt": "2017-08-08T20:20:14.397Z",
"Manufacturer": {
"objectId": "3NahYBNIiC",
"Manufacturer_Name": "ABC Ltd",
"createdAt": "2017-07-30T21:56:40.557Z",
"updatedAt": "2017-07-30T22:13:07.425Z",
"Devices": {
"__type": "Relation",
"className": "DeviceType"
},
"__type": "Object",
"className": "DeviceManufacturer"
},
"__type": "Object",
"className": "DeviceType"
},
...
}]
}
$scope.getDeviceItems = function () {
var query = new Parse.Query("Device");
query.include("Device_Type");
query.include("Device_Type.Manufacturer");
query.find({
success: function (results) {
$scope.deviceItems = [];
for (i = 0; i < results.length; i++) {
var curResult = results[i];
var d = curResult.Device_Type;
var m = curResult.Device_Type.Manufacturer;
var inventoryItem = {
deviceID: d.Device_ID
manufacturer: m.Manufacturer_Name
}
};
};
};
};
Not sure why a map is being used a regular JS object as shown above would work easier (assuming find function just resolved with the JS object from parsing the JSON instead of turning it into a Map object)
Using a Map you need to call get twice as far as I can tell to resolve "deeper" keys.
$scope.getDeviceItems = function () {
var query = new Parse.Query("Device");
query.include("Device_Type");
query.include("Device_Type.Manufacturer");
query.find({
success: function (results) {
$scope.deviceItems = [];
for (i = 0; i < results.length; i++) {
var curResult = results[i];
var d = curResult.get('Device_Type');
var m = curResult.get('Device_Type').get('Manufacturer'); // or d.get('Manufacturer')
var inventoryItem = {
deviceID: d.get('Device_ID')
manufacturer: m.get('Manufacturer_Name')
}
};
};
};
};
var testObj = new Map();
testObj.set('a', new Map());
testObj.get('a').set('b', 4);
console.log(testObj.get('a').get('b'))

JSON Data Fuzzy merge

I have a JSON data like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
},
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
}
}
I need to search for fuzzy data and merge. For example InvestmentsDeposits and InvestmentsDeposits$$$d need to be merged because it matches closely in name
Need to use javascript for this
For now I can make sure source data will always have $$$d at the end to merge with the target data without $$$d i.e., InvestmentDeposits.
My final merged content should be like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
"text": "newtext"
}
]
}
}
}
any help on this one?
What I have tried so far
var json0 = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
}
};
var json1 =
{
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
};
// Merge object2 into object1, recursively
$.extend( true, json0, json1 );
I am able to merge the data if i am able to split the InvestmentDeposits and InvestmentDeposits$$$d in to two distinct JSON objects but how to split and move the $$$d data in to another object? to make the jquery extend work
Use Object.keys() to find an object's keys and figure out what data to move over. You can compare the first key with the others to find matches, then remove the keys you just looked at until all of them are gone. Here's an example with a similar object.
var dat = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}, "InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
},
"NotLikeTheOthers": {
"Um": "Yeah."
}
};
var result = {}; // This will be the merged object
var keys = Object.keys(dat); // Contains keys
while(keys.length) {
var i=1;
for(; i<keys.length; i++) { // Find matches
if(keys[0] == keys[i] + '$$$d') { // Match type 1
result[keys[i]] = dat[keys[i]]; // Copy orig
for(var j in dat[keys[0]]) { // Replace values
result[keys[i]][j] = dat[keys[0]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
} else if(keys[i] == keys[0] + '$$$d') { // Reverse matched
result[keys[0]] = dat[keys[0]];
for(var j in dat[keys[i]]) {
result[keys[0]][j] = dat[keys[i]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
}
}
if(i > 0) { // Didn't find a match
result[keys[0]] = dat[keys[0]];
keys.shift();
}
}
alert(JSON.stringify(result));
Note that Object.keys() requires IE9+.

Categories

Resources