Reputation: 3181
I need to replace an object from in object tree, I tried several methods but I couldn't
let data = [
{
"accountId": 2
},
{
"accountId": 6,
"children": [{
"accountId": 8
}]
},
{
"accountId": 45
}
];
In above object array I need to replace ( when I know the accoundId
)
{
"accountId": 2
}
to
{
"accountId": 2,
"children": [
{
"accountId": 85
}
]
}
Is there any way(s)/library(s) to do that.
Upvotes: 1
Views: 936
Reputation: 8926
Plain javascript, using Array.prototype.map
function:
var data = [{ "accountId": 2 }, { "accountId": 6, "children": [{ "accountId": 8 }] }, { "accountId": 45 }];
var newData = { "accountId": 2, "children": [{ "accountId": 85 }] };
data = (function upd(data, n) {
return data.map(e => {
if (e.children) {
var o = {};
o.accountId = e.accountId;
o.children = upd(e.children, n);
return o;
}
else if (e.accountId == 8) {
return n;
} else return e;
});
})(data, newData);
document.write('<pre>' + JSON.stringify(data, 0, 2) + '</pre>');
Upvotes: 2
Reputation: 386620
You can use an iterative function for the search for the id and update of the array item.
function makeUpdate(a, u) {
return Array.isArray(a) && a.some(function (b,i,bb) {
if (b.accountId === u.accountId) {
bb[i] = u;
return true;
}
return makeUpdate(b.children, u);
});
}
var data = [{ "accountId": 2 }, { "accountId": 6, "children": [{ "accountId": 8 }] }, { "accountId": 45 }],
update = { "accountId": 8, "children": [{ "accountId": 85 }] };
makeUpdate(data, update);
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
Upvotes: 1