首页 > 解决方案 > 根据条件在对象内添加数据

问题描述

我有一个应用程序,其中有两种类型的数据:

  1. 玩具
    条件:

  {
    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:代码只是应用程序的模拟。

标签: javascript

解决方案


也许你想要这样的东西

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"));


推荐阅读