根据其他数组js更改数组中的值

时间:2020-09-29 12:47:16

标签: javascript arrays sorting

你好,我正在努力根据另一个数组来编辑数组中的某些值,我有这个:

tags = [
  { name: 'Music', value: 1, actif: 0 },
  { name: 'Sport', value: 2, actif: 0 },
  { name: 'Games', value: 3, actif: 0 },
  { name: 'Animals', value: 4, actif: 0 },
  { name: 'Party', value: 5, actif: 0 },
  { name: 'Arts', value: 6, actif: 0 },
  { name: 'Movies', value: 7, actif: 0 },
  { name: 'Travels', value: 8, actif: 0 },
  { name: 'Cooking', value: 9, actif: 0 },
  { name: 'Dance', value: 10, actif: 0 }
]
person = [
  { idui: 7619, iduser: 101, interest: 5 },
  { idui: 7620, iduser: 101, interest: 3 },
  { idui: 7621, iduser: 101, interest: 4 },
  { idui: 7622, iduser: 101, interest: 1 },
  { idui: 7623, iduser: 101, interest: 2 }
]

如果person.interest == tags.value,我想将tags.actif设置为1。我想我将不得不使用所有的find,但是我真的不知道该如何成功。

1 个答案:

答案 0 :(得分:1)

如果标签数组中的每个对象与标签值具有相同的兴趣,则可以将map标签中的每个对象actif更新为新对象。您可以使用array.find()方法

找到它

const tags = [
  { name: 'Music', value: 1, actif: 0 },
  { name: 'Sport', value: 2, actif: 0 },
  { name: 'Games', value: 3, actif: 0 },
  { name: 'Animals', value: 4, actif: 0 },
  { name: 'Party', value: 5, actif: 0 },
  { name: 'Arts', value: 6, actif: 0 },
  { name: 'Movies', value: 7, actif: 0 },
  { name: 'Travels', value: 8, actif: 0 },
  { name: 'Cooking', value: 9, actif: 0 },
  { name: 'Dance', value: 10, actif: 0 },
];

const persons = [
  { idui: 7619, iduser: 101, interest: 5 },
  { idui: 7620, iduser: 101, interest: 3 },
  { idui: 7621, iduser: 101, interest: 4 },
  { idui: 7622, iduser: 101, interest: 1 },
  { idui: 7623, iduser: 101, interest: 2 },
];

const changed = tags.map((tag) => {
  const person = persons.find(({ interest }) => interest === tag.value);
  
  return person ? {...tag, actif: 1} : tag;
});

console.log(changed);
.as-console-wrapper {max-height: 100% !important;}