javascript - 根据条件在对象内添加数据
问题描述
我有一个应用程序,其中有两种类型的数据:
- 人
- 玩具
条件:
- 用户可以将一个人分配给其中一个玩具,具体取决于:如果 toyType === 人的类型。例如,
{
name: "Lisa",
age: 7,
type: "F"
},
..不能用 toyType 分配给玩具M
,只能F
- 用户可以将一个人分配给一种玩具。
我的代码:
const info = [
{
name: "Bill",
age: 11,
type: "M"
},
{
name: "Lisa",
age: 7,
type: "F"
},
{
name: "Carl",
age: 17,
type: "M"
},
{
name: "John",
age: 8,
type: "M"
}
];
const toys = [
{
color: "red",
toyType: "M"
},
{
color: "white",
toyType: "F"
}
];
const thisPerson = { name: "Carl",age: 17};
function app(selectedtoyType) {
const result = toys.map((i) => {
if (selectedtoyType === i.toyType) {
return {
...i,
persons: toys.persons ? [...i.persons, thisPerson] : [thisPerson]
};
} else {
return { ...i };
}
});
return result;
}
console.log('1 time assign', app('M'))
console.log('2 time assign', app('M'))
我举了一个例子:const thisPerson = { name: "Carl",age: 17};
,我尝试分配他2次。
在这里我应该只在persons
数组中获取一个人,下次我应该在控制台中收到错误,我也应该能够将另一个人添加type M
到这个数组中,当然是与以前不同的人。
问题:我的代码有什么问题?
ps:代码只是应用程序的模拟。
解决方案
也许你想要这样的东西
const toys = [ { color: "red", toyType: "M", }, { color: "white", toyType: "F", }, ];
let ps = {};
const person = { name: "Carl", age: 17 };
function app(person, selectedtoyType) {
if (ps[person.name]) console.log("name alreasy used");
else {
toys.forEach((t) => {
if (selectedtoyType.toUpperCase() == t.toyType && !ps[person.name]) {
ps[person.name] = { ...person, ...t };
}
});
return Object.values(ps);
}
}
console.log("1 time assign", app(person, "M"));
console.log("2 time assign", app(person, "M"));
推荐阅读
- javascript - Javascript:乘法持久性问题提出的解决方案执行超时
- json - Spring MVC - 格式化为 JSON 的数据页,出现错误:无法推断 ResponseEntity<> 的类型参数
- java - 如何使用 putExtra() 和 getExtras() 代码获取 int 值?
- dart - Flutter 从 Firebase 存储中获取下载 URL
- python - 使用 Django / virtualenv 运行 celery 时找不到“__main__”模块
- c# - 创建宏时如何区分两个同名窗口
- angular - NGRX 角载荷或无载荷
- node.js - 更新 apollo-server-lambda npm 后,无服务器 lambda 不起作用
- android - 约束 2 个视图时的 ConstraintLayout 奇怪的属性行为
- java - 尝试读取文件时出现奇怪的 NoSuchFileException