我有点卡在这个问题上。
基本上我想在reqBody.address存在时更新db.address,如果不存在则使用现有值。 我目前不得不两次遍历我的db json;首先将变量设置为原始地址,然后在确定是否使用新创建的变量或reqBody.address时再次分配/合并。
我只想穿越一次。
除了显而易见的检查,只有当reqBody.address存在时我才会想知道这是否可以通过从assign中的函数返回值在单个语句中完成。
下面是我的代码到目前为止,我想要消除整个第一个db_address链命令,并让第二个链命令使用类似的东西:
.merge({ address: req_address || address } })
其中地址跟在||之后是原始值。
const _ = require('lodash')
const moment = require('moment');
let reqBody = {"address_list":[{"address_type":"Home","address":"99 West Street"}]}
let db = {"users":[{"id":1,"name":"Joe","address_list":[{"address_type":"Home","address":"11 High Street","created_date":"2018-01-08","updated_date":""}]}]}
let req_address = reqBody.address_list[0].address;
let db_address = _.chain(db)
.get('users').find({id: 1})
.get('address_list')
.filter((address) => {return address.address_type === reqBody.address_list[0].address_type})
.get('[0].address')
.value()
db_address = _.chain(db)
.get('users').find({id: 1})
.get('address_list')
.filter((address) => {return address.address_type === reqBody.address_list[0].address_type})
.get('[0]')
.merge({ address: req_address || db_address },
{ updated_date: moment().format() }
)
.value()
console.log(db_address)
提前致谢
干杯
PS:再次感谢Markus突出合并
答案 0 :(得分:1)
如果您只想更新db use .merge({ adress: req_address })
中的值,则不需要第一个链,如果值未定义,merge将不会覆盖:
如果目标值存在,则跳过解析为未定义的源属性。
这仍然会更新时间戳,但不确定这是否有问题。
或者,使用update
,即您要求的function funning inside assign
,也不允许更新时间戳。
带有merge
const _ = require('lodash')
const moment = require('moment');
let reqBody = {"address_list":[{"address_type":"Home","address":"99 West Street"}]}
let db = {"users":[{"id":1,"name":"Joe","address_list":[{"address_type":"Home","address":"11 High Street","created_date":"2018-01-08","updated_date":""}]}]}
let req_address = reqBody.address_list[0].address;
db_address = _.chain(db)
.get('users').find({id: 1})
.get('address_list')
.filter((address) => {return address.address_type === reqBody.address_list[0].address_type})
.get('0')
.merge({ address: req_address },
{ updated_date: moment().format() }
)
.value()
console.log(db_address)
带更新的版本
const _ = require('lodash')
const moment = require('moment');
let reqBody = {"address_list":[{"address_type":"Home","address":"99 West Street"}]}
let db = {"users":[{"id":1,"name":"Joe","address_list":[{"address_type":"Home","address":"11 High Street","created_date":"2018-01-08","updated_date":""}]}]}
let req_address = reqBody.address_list[0].address;
db_address = _.chain(db)
.get('users').find({id: 1})
.get('address_list')
.filter((address) => {return address.address_type === reqBody.address_list[0].address_type})
.update(
'0',
address =>
req_address ?
{
...address,
address: req_address,
updated_date: moment().format()
} :
address
)
.value()
console.log(db_address)
答案 1 :(得分:1)
在玩了一点之后,我只是添加了this
,它现在正在工作......太棒了。
.merge({ address: req_address || this.address },
{ updated_date: moment().format() }
)
干杯