update object array object
by John Allan
HTML
<div id="display"></div>
CSS
body {
font-family: 'Courier'
}
JavaScript
function log () {
var html, args;
args = Array.prototype.slice.call(arguments).join(' ');
html = $(['<div>', args, '</div>'].join(''));
$('#display').append(html);
}
viewModel = (function () {
var module;
module = {};
var view = {
'stuff': {
'reblasts': [
{
'guid': '1',
'liked': true
},
{
'guid': '2',
'liked': false
}
]
}
};
module.getReblast = function (index) {
return view.stuff.reblasts[index];
};
module.updateArticle = function (path, update) {
var node, i, l;
function getNode(obj, path) {
var node, pathArray, matchArray, matchProperty, matchValue, index;
pathArray = path.split('.');
shift = pathArray.shift();
if (shift.indexOf('|') >= 0) {
matchArray = shift.split('|');
matchProperty = matchArray[0];
matchValue = matchArray[1];
//is array
for (i = 0, l = obj.length; i < l; i++) {
if (obj[i][matchProperty] === matchValue) {
index = i;
break;
}
}
if (pathArray.length > 0) {
obj = obj[index];
node = getNode(obj, pathArray.join('.'));
} else {
//if we set the update here it works
obj[index] = update;
//if we return it and set the update outside it doesn't bubble up
node = obj[index];
}
} else {
//is object
if (pathArray.length > 0) {
obj = obj[shift];
node = getNode(obj,...