FoundUser是id为用户将新项目添加到该特定用户项目数组的用户。
const FoundUser = Object.keys(users)
.map(key => users[key])
.find(item => item.uid === uid)
console.log(FoundUser, 'current obj user')
UpUser是更新后的FoundUser对象,其中的项目已添加到特定用户项目数组中。
const itemobj = { name: "addeditem", price:330 }
const UpUser = {...FoundUser, items:FoundUser.items.concat([itemobj])}
console.log(UpUser, 'UpUser')
如何在不删除唯一键users
的情况下,仅在原始"97gbLdr4yyZljL75aZeVyoJraPo2"
对象中更新同一用户的对象。
const final = Object.assign({}, )
console.log(final, 'final')
用户数据如下所示。
state= {
{ "97gbLdr4yyZljL75aZeVyoJraPo2":
{
email:"some email",
items:[{name:'rose sherpa', price: 250}],
uid:'97gbLdr4yyZljL75aZeVyoJraPo2',
username:'someusername'
},
"47gbLdr412312312yyZljL75o2":
{
email:"some email2",
items:[{name:'black sherpa', price: 350}],
uid:'97gbLdr4yy1231123VyoJraPo2',
username:'someusername2'
}
}
}
所需的输出
{"97gbLdr4yyZljL75aZeVyoJraPo2":
{
email:"some email",
items:[{name:'rose sherpa', price: 250} , {name:'addeditem', price:330}],
uid:'97gbLdr4yyZljL75aZeVyoJraPo2',
username:'someusername'
},
"47gbLdr412312312yyZljL75o2":
{
email:"some email2",
items:[{name:'black sherpa', price: 350}],
uid:'97gbLdr4yy1231123VyoJraPo2',
username:'someusername2'
}
}
答案 0 :(得分:1)
与您更新items
FoundUser
的方式类似:
const final = { ...users, [FoundUser.uid]: UpUser }
顺便说一句Object.keys(users).map(key => users[key])
可以简化为Object.values(users)
。
答案 1 :(得分:1)
我可能将所有内容都折叠成一个函数:
const users = {"47gbLdr412312312yyZljL75o2": {"email": "some email2", "items": [{"name": "black sherpa", "price": 350}], "uid": "97gbLdr4yy1231123VyoJraPo2", "username": "someusername2"}, "97gbLdr4yyZljL75aZeVyoJraPo2": {"email": "some email", "items": [{"name": "rose sherpa", "price": 250}], "uid": "97gbLdr4yyZljL75aZeVyoJraPo2", "username": "someusername"}}
const addItem = (item, uid, users) =>
Object.values(users).find(user => user.uid === uid).items.push(item)
addItem({name:'addeditem', price:330}, '97gbLdr4yyZljL75aZeVyoJraPo2', users)
console.log(users)
或者如果您不能保证您想要的用户将被包含在列表中,那么
const addItem = (item, uid, users) => {
const user = Object.values(users).find(user => user.uid === uid)
if (user) {user.items.push(item)}
return users
}
(当然,如果user.items
可能不存在,可能会有另一项检查。)
我实际上偏好不可变数据,并且我自己可能会使用Ramda制作解决方案。 (免责声明:我是Ramda的作者)
const {map, when, propEq, evolve, append} = R
const users = {"47gbLdr412312312yyZljL75o2": {"email": "some email2", "items": [{"name": "black sherpa", "price": 350}], "uid": "97gbLdr4yy1231123VyoJraPo2", "username": "someusername2"}, "97gbLdr4yyZljL75aZeVyoJraPo2": {"email": "some email", "items": [{"name": "rose sherpa", "price": 250}], "uid": "97gbLdr4yyZljL75aZeVyoJraPo2", "username": "someusername"}}
const addItem = (item, uid, users) =>
map(when(propEq('uid', uid), evolve({items: append(item)})), users)
const newUsers = addItem({name:'addeditem', price:330}, '97gbLdr4yyZljL75aZeVyoJraPo2', users)
console.log(newUsers)
console.log(users) // unchanged
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>