Reputation: 773
How to find and replace over deep nested array object in javascript
I have a sample object name obj
and filtered the object by id, in , and out
(obj_res).
How to find and update the particular obj with id fund
in obj_res
in javascript as shown in expected output
I got stuck need help how to do in javascript
var obj_res = getValue("bank", "bank", "trans");
function getValue(send, receive, id){
const temp = obj.map(e => Object.entries(e).map(([k, val]) => val)).flat(3)
result_obj = temp.filter(x=>x.in ==send && && x=>x.out ==receive && x.id == id);
return result_obj;}
//whole object input
var obj = [{
"btob": [{
"id": "trans",
"in": "bank",
"out": "bank",
"value": 10,
},{
"id": "fund",
"in": "bank",
"out": "bank",
"value": 10
}],
"ctob": [{
"id": "trans",
"in": "credit",
"out": "bank",
"value": 20
},{
"id": "fund",
"in": "credit",
"out": "bank",
"value": 10
}]
}]
//resultant obj after filter by id , in ,out
var obj_res =[{
"id": "trans",
"in": "bank",
"out": "bank",
"value": 10
},{
"id": "fund",
"in": "bank",
"out": "bank",
"value": 10
}]
Expected Output:
res=[{
"id": "trans",
"in": "bank",
"out": "bank",
"value": 10
},{
"id": "fund",
"in": "credit",
"out": "bank",
"value": 10
}]
Upvotes: 1
Views: 3702
Reputation: 867
A little bit late to the party, heh. I needed to modify deeply nested objects too, and found no acceptable tool for that purpose. Then I've made this and pushed it to npm.
https://www.npmjs.com/package/find-and
This small lib can help with modifying nested objects in a lodash manner. E.g.,
var findAnd = require("find-and");
const obj_res =[{
"id": "trans",
"in": "bank",
"out": "bank",
"value": 10
},{
"id": "fund",
"in": "bank",
"out": "bank",
"value": 10
}];
findAnd.changeProps(obj_res, { id: 'fund' }, { in: 'credit' });
outputs exactly what you want.
https://runkit.com/arfeo/find-and
Hope this could help someone else.
Upvotes: 2
Reputation: 171690
Use find()
to get first instance if you think there is only one. Otherwise use filter()
and loop over each to modify properties on each matching object
var obj_res = [{
"id": "trans",
"in": "bank",
"out": "bank",
"value": 10
}, {
"id": "fund",
"in": "bank",
"out": "bank",
"value": 10
}]
var fund = obj_res.find(({id}) => id === 'fund'); // returns array element or false
if (fund) {
fund.in = 'XXXXX';
console.log(obj_res)
}
Upvotes: -1