如何在数组中的对象中找到具有特定值的键,然后将该键与该值交换?
我的目标是编写一个遍历对象数组的脚本。它需要找到值为“age”的键,以便“age”成为键,数字成为值。那么就需要对其进行改造。重新格式化工作得很好,但如果没有 for 循环,我无法更改标签,这不是作业所要求的。
我当前的代码如下所示:
function mapCharacters(comiccharacters) {
const supers = comiccharacters.map(({ name, isHero, age}) => {
for (let i = 0; i < comiccharacters.length; i++)
{
for (var key in comiccharacters[i])
{
if (comiccharacters[i][key] === 'age')
{
[key, comiccharacters[i][key]] = [comiccharacters[i][key], key]
}
}
}
if (isHero == true) {
console.log(age);
return "hero: " + name + ", age: " + age;
}
else {
return "villain: " + name + ", age: " + age;
}
});
console.log(supers);
}
mapCharacters([
{ name: 'Spider-Man', isHero: true, '28': 'age' },
{ name: 'Thor', isHero: true, '1500': 'age' },
{ name: 'Black Panther', isHero: true, '35': 'age' },
{ name: 'Loki', isHero: false, '1054': 'age' },
{ name: 'Venom', isHero: false, 'unknown': 'age' }
])
但是,我对 for 循环所做的操作,我需要对映射函数进行操作。我想知道如何
My goal is to write a script that goes though an array of objects. It needs to find the keys with the value "age," so that "age" become the key, and the numbers become the values. It then needs to be reformated. The reformating works just fine, but I can't change the tags without a for loop, which is not what the assignment asks.
My current code looks like this:
function mapCharacters(comiccharacters) {
const supers = comiccharacters.map(({ name, isHero, age}) => {
for (let i = 0; i < comiccharacters.length; i++)
{
for (var key in comiccharacters[i])
{
if (comiccharacters[i][key] === 'age')
{
[key, comiccharacters[i][key]] = [comiccharacters[i][key], key]
}
}
}
if (isHero == true) {
console.log(age);
return "hero: " + name + ", age: " + age;
}
else {
return "villain: " + name + ", age: " + age;
}
});
console.log(supers);
}
mapCharacters([
{ name: 'Spider-Man', isHero: true, '28': 'age' },
{ name: 'Thor', isHero: true, '1500': 'age' },
{ name: 'Black Panther', isHero: true, '35': 'age' },
{ name: 'Loki', isHero: false, '1054': 'age' },
{ name: 'Venom', isHero: false, 'unknown': 'age' }
])
However, what I did with the for loop, I need to do with map functions. I would like advice as to how
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您必须循环遍历数组。然后对于每个对象键,检查值是否为
age
。找到后,从对象中删除该属性,并使用键age
和值key
设置一个新属性。First you have to loop throught the array. Then for each object key, check if the value is
age
. When found, delete the property from the object and set a new one with the keyage
and the valuekey
.