Reputation: 4370
I have an object called "x" and the format is given below:
var x = [{
name: "a",
item:[{
name: "b",
item:[{
name: "c",
item:[{
name:"f"
}]
},{
name: "d",
item:[{
name: "e"
}]
}]
}]
},{
name: "a",
item:[{
name: "b",
item:[{
name: "c"
}]
}]
}];
and now i push some element inside this object. For example:
x[0].item[0].name = "x";
x[0].item[0].item[0].name = "y";
x[0].item[0].item[0].item[0].name = "z";
So, Here is my question. I pushed three element inside the object. The code for that is given above and all the three code are similar, only the number of "items" is changed. Example: in 1st code, only one "item" is used and in the next, two "items" and next,three items.
So, is there any efficient way to create a common function to push the element inside the object (or) like in Array, can we push like x[0].items[[0][0]] = "y"
. ?
Here is the jsFiddle link.
Upvotes: 2
Views: 84
Reputation: 386550
Version without error handling
Preliminary note: I assume, that you always have [n]
or [n].item[m]
structure. The algorithm does not have any error handling.
The needed array is evaluated as follows: Take the first element and get the object. Get the next element and before applying the element get the item
property first. Then apply the array index. Repeat. After finishing the loop apply the value to the name
property.
var x=[{name:"a",item:[{name:"b",item:[{name:"c",item:[{name:"f"}]},{name:"d",item:[{name:"e"}]}]}]},{name:"a",item:[{name:"b",item:[{name:"c"}]}]}];
function push(o, a, v) {
a.forEach(function (el, i) {
i && (o = o.item);
o = o[el];
});
o.name = v;
}
push(x, [0, 0, 0], 'y');
document.getElementById('out').innerHTML = JSON.stringify(x, null, 4);
<pre id="out"></pre>
Version with error handling
Assuming nothing. If not well formed it throws exception when property item
is not given or index of array is out of bound.
var x=[{name:"a",item:[{name:"b",item:[{name:"c",item:[{name:"f"}]},{name:"d",item:[{name:"e"}]}]}]},{name:"a",item:[{name:"b",item:[{name:"c"}]}]}];
function getReference(o, a) {
a.forEach(function (el, i) {
if (i) {
if ('item' in o) {
o = o.item;
} else {
throw new Error('No Reference (item)');
}
}
if (o[el]) {
o = o[el];
} else {
throw new Error('No Reference (index: ' + el + ')');
}
});
return o;
}
// working
try {
getReference(x, [0, 0, 0, 0]).name = 'z';
} catch (ex) {
alert(ex);
}
// throws exception 'No Reference (index: 3)'
try {
getReference(x, [0, 0, 0, 3]).name = '*';
} catch (ex) {
alert(ex);
}
document.getElementById('out').innerHTML = JSON.stringify(x, null, 4);
<pre id="out"></pre>
Upvotes: 2