如何在javascript中查找和替换深层嵌套数组对象
我有一个示例对象名称obj
,并用id, in , and out
(obj_res)过滤了该对象。
如预期的输出所示,如何在JavaScript的id fund
中使用obj_res
查找和更新特定的obj
我陷入困境需要帮助,该如何使用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
}]
答案 0 :(得分:1)
晚些晚了,嘿。我也需要修改深层嵌套的对象,并且找不到用于此目的的可接受工具。然后,我将其制成并将其推送到npm。
https://www.npmjs.com/package/find-and
这个小库可以帮助以Lodash的方式修改嵌套对象。例如,
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' });
精确地输出您想要的。
https://runkit.com/arfeo/find-and
希望这可以帮助其他人。
答案 1 :(得分:0)
如果您认为只有一个,请使用find()
获得一审。否则,请使用filter()
并遍历每个对象以修改每个匹配对象的属性
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)
}