nested html list to json - html

[
{
"tree_id": 6,
"fields" : ["id","lft", "rgt"], // tree_id is stripped if requested via fields because redundant
"values" :
[1,1,4,[
[2,2,3,[]]
]]
}
// more could follow ...
]
above is the json code that Bobab uses to export/import nested sets.
Baobab nested set json export/import format
How can i parse a nested html list to yield json like above?
I am trying to manipulate nested lists using drag and drop
Nestable list
It has 2 functions that kind of do what i want to achieve, but my head keeps twisting around it.
toHierarchy: function(options) {
var o = $.extend({}, this.options, options),
sDepth = o.startDepthCount || 0,
ret = [];
$(this.element).children(o.items).each(function () {
var level = _recursiveItems(this);
ret.push(level);
});
//console.log(JSON.stringify(ret));
return ret;
function _recursiveItems(item) {
var id = ($(item).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
if (id) {
var currentItem = {"id" : id[2]};
if ($(item).children(o.listType).children(o.items).length > 0) {
currentItem.children = [];
$(item).children(o.listType).children(o.items).each(function() {
var level = _recursiveItems(this);
currentItem.children.push(level);
});
}
return currentItem;
}
}
},
toArray: function(options) {
var o = $.extend({}, this.options, options),
sDepth = o.startDepthCount || 0,
ret = [],
left = 2;
ret.push({
"item_id": o.rootID,
"parent_id": 'none',
"depth": sDepth,
"left": '1',
"right": ($(o.items, this.element).length + 1) * 2
});
$(this.element).children(o.items).each(function () {
left = _recursiveArray(this, sDepth + 1, left);
});
ret = ret.sort(function(a,b){ return (a.left - b.left); });
//console.log(JSON.stringify(ret));
return ret;
function _recursiveArray(item, depth, left) {
var right = left + 1,
id,
pid;
if ($(item).children(o.listType).children(o.items).length > 0) {
depth ++;
$(item).children(o.listType).children(o.items).each(function () {
right = _recursiveArray($(this), depth, right);
});
depth --;
}
id = ($(item).attr(o.attribute || 'id')).match(o.expression || (/(.+)[-=_](.+)/));
if (depth === sDepth + 1) {
pid = o.rootID;
} else {
var parentItem = ($(item).parent(o.listType)
.parent(o.items)
.attr(o.attribute || 'id'))
.match(o.expression || (/(.+)[-=_](.+)/));
pid = parentItem[2];
}
if (id) {
ret.push({"item_id": id[2], "parent_id": pid, "depth": depth, "left": left, "right": right});
}
left = right + 1;
return left;
}
},

If your goal is to insert that data on the database using the Baobab library then you do not need to create the JSON code with the left/right indexes yourself, which can be fairly complicated to do.
Just send to the server tree structured data and on server side iterate over it adding the objects to the database.
You could create a generic tree structure with something like this (using jQuery to have a shorter example):
function genTree(domNode){
var parentObj = {
data : { /* filled with data found in domNode, e.g. the baobab node id */ },
children: []
};
$(domNode).find('> li, > ul > li').each(function(){
parentObj.children.push(genTree(this));
});
return parentObj;
}
Then when you'll travel the structure you will use the Baobab API to add the nodes to your database (at that point you can export it to JSON if you really need it)

Related

Google-Apps-Script Convert XML to JSON

I've got an XML string, like this:
'<ALEXA VER="0.9" URL="davidwalsh.name/" HOME="0" AID="="><SD TITLE="A" FLAGS="" HOST="davidwalsh.name"><TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/><LINKSIN NUM="1102"/><SPEED TEXT="1421" PCT="51"/></SD><SD><POPULARITY URL="davidwalsh.name/" TEXT="7131"/><REACH RANK="5952"/><RANK DELTA="-1648"/></SD></ALEXA>'
I'd like to convert it into JSON format:
{
"ALEXA":{
"#attributes":{
"VER":"0.9",
"URL":"davidwalsh.name/",
"HOME":"0",
"AID":"="
},
"SD":[
{
"#attributes":{
"TITLE":"A",
"FLAGS":"",
"HOST":"davidwalsh.name"
},
"TITLE":{
"#attributes":{
"TEXT":"David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"
}
...
I've found lot's of solutions for js, but none of them worked in google-apps-script.
I've also seen this question:
Parsing XML on a Google Apps script
but it does not exactly my case: I'de like to parse any XML into JSON, not just the provided sample.
I've found own solution (in the answer), and not sure it matches all cases.
I thought the solution should be a recursion function. After some research, I've found this great code by David Walsh and was able to adopt it. Here's what I've come to:
// Changes XML to JSON
// Original code: https://davidwalsh.name/convert-xml-json
function xmlToJson_(xml) {
// Create the return object
var obj = {};
// get type
var type = '';
try { type = xml.getType(); } catch(e){}
if (type == 'ELEMENT') {
// do attributes
var attributes = xml.getAttributes();
if (attributes.length > 0) {
obj["#attributes"] = {};
for (var j = 0; j < attributes.length; j++) {
var attribute = attributes[j];
obj["#attributes"][attribute.getName()] = attribute.getValue();
}
}
} else if (type == 'TEXT') {
obj = xml.getValue();
}
// get children
var elements = [];
try { elements = xml.getAllContent(); } catch(e){}
// do children
if (elements.length > 0) {
for(var i = 0; i < elements.length; i++) {
var item = elements[i];
var nodeName = false;
try { nodeName = item.getName(); } catch(e){}
if (nodeName)
{
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson_(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson_(item));
}
}
}
}
return obj;
};
I've posted the sample on GitHub.
Usage:
var xml = XmlService.parse(xmltext);
Logger.log(JSON.stringify(xmlToJson_(xml)));
Reference:
XmlService
The original answer didn't work for me. There may have been a change in the apps script XML API but it wouldn't include the text content of a node without children. Here is the code I wrote that seems to work well.
Note, it outputs in a slightly different fashion than the example you provided. I found that this might be a more consistent format for a broader range of use cases. I also found that including the attributes wasn't necessary for everything I was doing and created clutter, so I've included a version that doesn't parse attributes.
If you include attributes, the output follows this pattern:
{foo:{attributes:{...},content:{...}}
To Include Attributes:
function xmlParse(element) {
/*
* Takes an XML element and returns an object containing its children or text
* If children are present, recursively calls xmlTest() on them
*
* If multiple children share a name, they are added as objects in an array
* If children have unique names, they are simply added as keys
* i.e.
* <foo><bar>one</bar><baz>two</baz></foo> === {foo: {bar: 'one', baz: 'two'}}
* <foo><bar>one</bar><bar>two</bar></foo> === {foo: [{bar: 'one'},{bar: 'two'}]}
*/
let obj = {}
const rootName = element.getName();
// Parse attributes
const attributes = element.getAttributes();
const attributesObj = {};
for(const attribute of attributes) {
attributesObj[attribute.getName()] = attribute.getValue();
}
obj[rootName] = {
attributes: attributesObj,
content: {}
}
const children = element.getChildren();
const childNames = children.map(child => child.getName());
if (children.length === 0) {
// Base case - get text content if no children
obj = {
content: element.getText(),
attributes: attributesObj
}
} else if (new Set(childNames).size !== childNames.length) {
// If nonunique child names, add children as an array
obj[rootName].content = [];
for (const child of children) {
if (child.getChildren().length === 0) {
const childObj = {};
childObj[child.getName()] = xmlParse(child);
obj[rootName].content.push(childObj)
} else {
const childObj = xmlParse(child);
obj[rootName].content.push(childObj)
}
}
} else {
// If unique child names, add children as keys
obj[rootName].content = {};
for (const child of children) {
if (child.getChildren().length === 0) {
obj[rootName].content[child.getName()] = xmlParse(child);
} else {
obj[rootName].content = xmlParse(child);
}
}
}
return obj;
}
Without Attributes:
function xmlParse(element) {
/*
* Takes an XML element and returns an object containing its children or text
* If children are present, recursively calls xmlTest() on them
*
* If multiple children share a name, they are added as objects in an array
* If children have unique names, they are simply added as keys
* i.e.
* <foo><bar>one</bar><baz>two</baz></foo> === {foo: {bar: 'one', baz: 'two'}}
* <foo><bar>one</bar><bar>two</bar></foo> === {foo: [{bar: 'one'},{bar: 'two'}]}
*/
let obj = {}
const rootName = element.getName();
const children = element.getChildren();
const childNames = children.map(child => child.getName());
if (children.length === 0) {
// Base case - get text content if no children
obj = element.getText();
} else if (new Set(childNames).size !== childNames.length) {
// If nonunique child names, add children as an array
obj[rootName] = [];
for (const child of children) {
if (child.getChildren().length === 0) {
const childObj = {};
childObj[child.getName()] = xmlParse(child);
obj[rootName].push(childObj)
} else {
const childObj = xmlParse(child);
obj[rootName].push(childObj)
}
}
} else {
// If unique child names, add children as keys
obj[rootName] = {};
for (const child of children) {
if (child.getChildren().length === 0) {
obj[rootName][child.getName()] = xmlParse(child);
} else {
obj[rootName] = xmlParse(child);
}
}
}
return obj;
}
Usage for both of these:
const xml = XmlService.parse(xmlText);
const rootElement = xml.getRootElement();
const obj = xmlParse(rootElement);
const asJson = JSON.stringify(obj);
Reference:
XMLService

How to set one more level in Object of a not predefined item?

The main issue is the following:
Get JSON from the server
Put data to form
Serialize form
Create JSON with correct structure
Send it to the server
I have difficulties on the fourth step, what I've done:
methods: {
onSubmit: function() {
var dataForm = new FormData(this.$refs['form']);
var data = [];
for (var _iterator = dataForm.entries(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _Object$assign;
var _Helper = {};
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _ref2 = _ref,
key = _ref2[0],
val = _ref2[1];
Object.assign(_Helper, (_Object$assign = {}, _Object$assign[key] = val, _Object$assign));
}
}
},
Here you go - a link to the codepen.
As you can see I could create JSON like that:
{"0":"a","1":"b","2":"c","3":"d","4":"e","5":"d"}
However, I need smth like that:
{
"0": {
"text": "a"
},
"1": {
"text": "b"
},
"2": {
"text": "c"
},
"3": {
"text": "d"
},
"4": {
"text": "e"
},
"5": {
"text": "d"
}
}
What Can I do to implement it and also keep the correct structure of my JSON?
To change the format, change in the location it assigns the property value:
Object.assign(data, (_Object$assign = {}, _Object$assign[key] = {text: val}, _Object$assign));
// -------------------------------------------------------------^^^^^^^^^^^
Instead of a string (val), assign the object in the format you want ({text: val}).
Updated CodePen.
If you can use modern (ES6) JavaScript, there's a much shorter notation for that:
var [key, val] = _ref;
Object.assign(data, {[key]: {text: val}});
CodePen here.
Or (because you are using FormData#entries() you do are using modern JS):
var formData = Array.from(new FormData(this.$refs['form']).entries());
var data = Object.assign(...formData.map(([key, val]) => ({[key]: {text: val}})));
console.log(JSON.stringify(data));
Targetting IE10 and above
To target IE10 and above you'll need polyfills. The problem is not the syntax, but the absence of functions like .entries(), that will be added by the polyfills. To use the least amount possible of polyfills, you'll have to iterate the iterator "manually" (kind of like you are already). For more info, check this answer.
You can do the whole construction much more simply:
onSubmit: function () {
const dataForm = new FormData(this.$refs['form']);
const data = {};
for (const i of dataForm.entries()) {
data[i[0]] = { text: i[1] }
}
console.log(JSON.stringify(data));
}

Delete token from SAPUI5 Multi Input Field with Data Binding

in my SAPUI5 app I am using a Multi Input Field with tokens which are bound to a JSON Model. Newly added entries are saved in the JSON Model. However, when deleting a token by pressing the "x" next to the token text, the token disappears from the multi input field. But when adding a new token the deleted one reappears.
How can I ensure that the deleted entry is also deleted from the JSON Model?
This is my current code for adding the token to the model:
multiInputField.addValidator(function(args){
MessageBox.confirm("Do you really want to add Token\"" + args.text + "\"?", {
onClose: function(oAction) {
if (oAction === MessageBox.Action.OK){
var oToken = new Token({key: args.text, text: args.text});
args.asyncCallback(oToken);
var aFields = sap.ui.getCore().getView().getModel("myModel").getProperty("/Tokens");
var oNewFields= {
Tokens: args.text
};
aFields .push(oNewFields);
sap.ui.getCore().getView().getModel("myModel").setProperty("/Tokens", aFields );
sap.ui.getCore().getView().getModel("myModel").refresh();
} else {
args.asyncCallback(null);
}
},
title: "Add Token"
});
return sap.m.MultiInput.WaitForAsyncValidation;
});
I guess we can use "tokenUpdate" event for this.
For example, given that I have this MultiInput in my view:
<MultiInput width="500px" id="multiInput" suggestionItems="{ path: 'dataModel>/data'}" showValueHelp="true" tokenUpdate="onTokenUpdate">
<core:Item key="{dataModel>key}" text="{dataModel>value}"/>
</MultiInput>
then in my controller I can handle this like :
onTokenUpdate: function(oEvent) {
var sType = oEvent.getParameter("type");
if (sType === "removed") {
var sKey = oEvent.getParameter("removedTokens")[0].getProperty("key");
var oModel = this.getView().getModel("dataModel");
var aData = this.getView().getModel("dataModel").getProperty("/data");
for (var i = 0, len = aData.length; i < len; i++) {
var idx;
console.log(sKey + "-" + aData[i].key);
if (aData[i].key === sKey) {
idx = i;
}
}
aData.splice(idx, 1);
oModel.setProperty("/data", aData);
console.log(oModel);
}
}
And this is my json:
{
"data": [
{
"key": "token1",
"value": "token1"
},
{
"key": "token2",
"value": "token2"
}
]
}

Passing a JSON AngularJS structure to a mongoDB database

I have just recentely used AngularJS to "convert" a data structure I had in pure SVG format into JSON format.
Now, I want to store such a structure in a MongoDB database to start finally connecting some components of the MEAN stack together and start seeing some things working! Basically, I have the following code inside a Webstorm AngularJS project:
JS:
var app = angular.module('app', []);
var RectangleDim=30;
app.controller('MainCtrl', function($scope) {
$scope.graph = {'width': 5000, 'height': 5000};
$scope.circles = [
/* JSON.parse("{\"x\": 85, \"y\": 20, \"r\":15}"),
{"x": 20, "y": 60, "r":20},
{"x": 18, "y": 10, "r":40} */
];
$scope.draw=function(val)
{
// val = document.getElementById("NumQuest").value;
return JSON.parse('{\"cx\":'+val+', "cy": 20, "r":30}');
// $scope.circles.push(JSON.parse('{\"x\":'+val+', "y": 220, "r":30}'));
};
$scope.rectangles = [
// {'x':220, 'y':220, 'width' : 300, 'height' : 100},
// {'x':520, 'y':220, 'width' : 10, 'height' : 10},
];
$scope.DrawRect=function(xpos,ypos) {
return JSON.parse('{\"x\":' + xpos + ', \"y\":' + ypos + ', \"width\":' + RectangleDim + ', \"height\":' + RectangleDim+ '}');
};
$scope.Debug=function(desiredNo){
desiredNo=document.getElementById("NumQuest").value;
for(var i = 0;i < RectangleDim*desiredNo+desiredNo;i++){
$scope.rectangles.push($scope.DrawRect(i+RectangleDim+1,40));
}
};
$scope.DrawLineOdd=function(desiredNo,lineNo,pozY){
var pozX = lineNo*RectangleDim;
var aux = 2*Math.floor(Math.sqrt(desiredNo))-1-2*lineNo;
for (var j = 0; j < aux; j++) {
$scope.rectangles.push($scope.DrawRect(pozX, pozY));//$scope.DrawRect(pozX, pozY);
pozX += RectangleDim;
}
//return aux;
};
$scope.DrawMatrixPerfectProgression=function(desiredNo) {
desiredNo=document.getElementById("NumQuest").value;
var line=0;
var pozy=0;
while(line<Math.floor(Math.sqrt(desiredNo))) {
$scope.DrawLineOdd(desiredNo, line, pozy);
//document.getElementById("val").innerHTML = teste;
line += 1;
pozy+=RectangleDim;
}
//document.getElementById('tablePrint').innerHTML = finalTable;
};
$scope.DrawLineEven=function(desiredNo, lineNo, pozY){
var pozX = lineNo*RectangleDim;
//var pozY = lineno*20;
var aux = 2*Math.floor(Math.sqrt(desiredNo))-2*lineNo;
for (var j = 0; j < aux; j++) {
$scope.rectangles.push($scope.DrawRect(pozX, pozY));
pozX += RectangleDim;
}
//return aux;
};
$scope.DrawMatrixEvenProgression=function(desiredNo) {
desiredNo=document.getElementById("NumQuest").value;
var line=0;
var pozy=0;
while(line<Math.floor((Math.sqrt(4*desiredNo+1)-1)/2)) {
$scope.DrawLineEven(desiredNo, line, pozy);
//document.getElementById("val").innerHTML = teste;
line += 1;
pozy+=RectangleDim;
}
//document.getElementById('tablePrint').innerHTML = finalTable;
};
$scope.AddExtraRectangles=function(desiredNo) {
desiredNo = document.getElementById("NumQuest").value;
var arg1 = desiredNo - ( Math.floor(Math.sqrt(desiredNo))*Math.floor(Math.sqrt(desiredNo)));
var arg2 = desiredNo-(Math.floor((Math.sqrt(4*desiredNo+1)-1)/2)*Math.floor((Math.sqrt(4*desiredNo+1)-1)/2))-Math.floor((Math.sqrt(4*desiredNo+1)-1)/2);
var OptimalLeftOver = Math.min( arg1 ,arg2 );
//We add two rectangles per row: one at the beginning one at the end
//we start with the row below the first one
var line;
var pozy;
var pozx1, pozx2;
var nRectLine_i;
if(OptimalLeftOver===arg1){
line=1;//1st line is skipped
pozy=RectangleDim;
pozx1 = 0;
while(OptimalLeftOver>0) {
nRectLine_i = 2* Math.floor(Math.sqrt(desiredNo))-1-2*line;
pozx2 = (line-1)*RectangleDim+RectangleDim*(nRectLine_i+1);//pozx1+nRectLine_i+2*RectangleDim;
$scope.rectangles.push($scope.DrawRect(pozx1,pozy));
OptimalLeftOver-=1;
if(OptimalLeftOver>0) {
$scope.rectangles.push($scope.DrawRect(pozx2, pozy));
OptimalLeftOver -= 1;
}
//document.getElementById("val").innerHTML = teste;
line += 1;
pozy+=RectangleDim;
pozx1=RectangleDim*line - RectangleDim;
}
//document.getElementById('tablePrint').innerHTML = finalTable;
}
else {
line=1;//1st line is skipped
pozy=RectangleDim;
pozx1 = 0;
while(OptimalLeftOver>0) {
nRectLine_i = 2* Math.floor(Math.sqrt(desiredNo))-2*line;
pozx2 = RectangleDim*(line-1)+RectangleDim*(nRectLine_i+1);//pozx1+nRectLine_i+2*RectangleDim;
$scope.rectangles.push($scope.DrawRect(pozx1,pozy));
OptimalLeftOver-=1;
if(OptimalLeftOver>0) {
$scope.rectangles.push($scope.DrawRect(pozx2, pozy));
OptimalLeftOver -= 1;
}
//document.getElementById("val").innerHTML = teste;
line += 1;
pozy+=RectangleDim;
pozx1=RectangleDim*line - RectangleDim;
}
//document.getElementById('tablePrint').innerHTML = finalTable;
}
};
/* $scope.DrawMatrix=function(desiredNo)
{
/* Chooses optimal leftover number based on the progression formulas.
Attempts to minimize the work of the designer of the response form without
making too much assumptions
desiredNo = document.getElementById("NumQuest").value;
var arg1 = desiredNo - ( Math.floor(Math.sqrt(desiredNo))*Math.floor(Math.sqrt(desiredNo)));
var arg2 = desiredNo - (Math.floor((Math.sqrt(4*desiredNo+1)-1)/2)*Math.floor((Math.sqrt(4*desiredNo+1)-1)/2))-Math.floor((Math.sqrt(4*desiredNo+1)-1)/2);
var OptimalLeftOver = Math.min( arg1 ,arg2 );
document.getElementById("val").innerHTML = 'There are '+OptimalLeftOver+' questions missing!'+ arg1+ '___'+arg2;
console.log(arg1);
if(OptimalLeftOver===arg1){
DrawMatrixPerfectProgression(desiredNo);
AddExtraRectangles(desiredNo);
}
else {
DrawMatrixEvenProgression(desiredNo);
AddExtraRectangles(desiredNo);
}
}; */
}
);
angular.bootstrap(document.getElementById('body'), ["app"]);
The relevant part of the code is the $scope.rectangles array which contains the JSON.parse of the strings representing my data structure on the html side and that structure in JSON (or JSON parsed or whatever) is what I want to save in the MongoDB database...How can I do that? The HTML relevant part is just like this:
HTML:
<p><button ng-click="DrawMatrixEvenProgression(NumQuest)">Draw</button></p>
<svg ng-attr-height="{{graph.height}}" ng-attr-width="{{graph.width}}">
<rect ng-repeat="rect in rectangles"
ng-attr-x="{{rect.x}}"
ng-attr-y="{{rect.y}}"
ng-attr-width="{{rect.width}}"
ng-attr-height="{{rect.height}}">
</rect>
</svg>
Any help will be appreciated... Can I start by adding more files to that project to handle the database and then things will be linked together?
Like adding stuff to handle the mongoose and the connections?
Thanks in advance!
Because Angular is a front-end framework. So to communicate with database (in this case MongoDB) you need to have application on the server-side to handle this and I suggest you to use Node.js and Mongoose as a MongoDB driver.
Node.js
Mongoose
Come back to Angular, you can create Angular service or factory and let the them talk to your server with service like $http or $resource.
Angular service documentation
Example for angular service
angular.module('app')
.factory('RectangleService', function($http){
return {
create: create
}
function create(rectangle){
// make http request to the server
return $http({
url: 'API_URL',
method: 'GET',
params: rectangle
});
}
});
After you create your service you have to inject it to your controller and
you may create some function to your $scope to talk with service like this
app.controller('MainCtrl', function($scope, RectangleService) { // <-- Inject service to controller
// your controller code
$scope.createRectangle = function(rectangle){
RectangleService.create(rectangle);
}
});
You can map createRectangle function to directive like ng-click and pass your json data as a parameter
Because I don't know what server-side language you can use, so I don't come with an example for Node.js & Mongoose
Hope this can help :)

merge json object with arrays

Suppose I have two json objects and I need to merge them.
css: [{
drag: "mode() == 'layout'",
ui_draggable: "mode() == 'layout'"
}]
css: [{
someclass : true
}]
I want to end up with:
css: [{
drag: "mode() == 'layout'",
ui_draggable: "mode() == 'layout'",
someclass : true
}]
After some further trial I came up with this but I assume I have place a few bugs or useless lines of code in it.
I came up with this code after a little playing around. My needs didn't need to recurse more than two levels so this is just fine. It could be much refined I am sure but it works great for binding knockout. Here is an example of how I used it to extend jquery unobtrusive knockoutjs
var settings = {
text: 'SelectedCard().CardData.Title',
visible: "mode() != 'edit' || !isMyCard()",
css: [{ drag: "mode() == 'layout'" , selectedElement: "selectedCardElement() == '_titlePreview'"}]
};
var settings2 =
{
css: [{ drag: "mode() == 'layout'"}]
};
var settings3 = merge(settings, settings2);
function merge(first, second) {
for (var a1 in first) {
// if second object is null we are finished.
used.push(a1);
if (second[a1] == null) {
continue;
} else {
var ob2 = second[a1];
if (typeof (first[a1]) != typeof (ob2)) {
throw new Error("conflicting properties named:" + a1);
}
if ($.isArray(first[a1])) {
for (var i = 0; i < ob2.length; i++) {
first[a1].push(ob2[i]);
}
} else {
// matching property.
return merge(first[a1], second[a1]);
}
}
}
for (var a2 in second) {
if (used.indexOf(a2) < 0) {
first[a2] = second[a2];
}
}
return first;
}
1) To merge both objects with a one-way overwrite, this will do it:
for (var attrname in obj2) {
obj1[attrname] = obj2[attrname];
}
2) To merge selectively, both ways:
obj1.someclass = obj2.someclass;
-or-
obj2["someclass"] = obj1["someclass"];
In this case, if the property does not yet exist in the object it does not need to be defined before assigning it.
3) Consider using a library like Underscore.js for performing "array functions" similar to this:
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
returns [1, 2, 3, 101, 10]
4) Lastly, here's a strong resource for formatting JSON objects, arrays and a combination thereof: jsonexample.com. This will be helpful as you get into complex "array functions".
Cheers!