如何将数组中的一个对象替换为另一个对象?

huangapple go评论72阅读模式
英文:

How to replace an object in an array with another object?

问题

在Vue.js中,我正在寻找一种方法来将数组中的 social 替换为具有相同值的另一个对象的键,例如:

netTeams: {
    0: {
        social: 'Twitter',
        name: 'Red',
        id: 32,
        group: 'a'
    },
    1: {
        social: 'Twitter',
        name: 'Green',
        id: 33,
        group: 'b'
    }
}

socials: {
    1: 'Facebook',
    2: 'Instagram',
    3: 'Twitter',
    4: 'Youtube'
}

结果应该是:

netTeams: {
    0: {
        social: 3,
        name: 'Red',
        id: 32,
        group: 'a'
    },
    1: {
        social: 3,
        name: 'Green',
        id: 33,
        group: 'b'
    }
}

我尝试使用计算属性,但遇到了错误。任何建议将不胜感激!

英文:

In vue.js I am looking for a way to replace social in the array with another object's key with the same value, for example:

netTeams: {
            0: {
                social: 'Twitter',
                name: 'Red',
                id: 32,
                group: 'a'
            },
            1: {
                social: 'Twitter',
                name: 'Green',
                id: 33,
                group: 'b'
            }
        }

and

socials: {
            1: Facebook,
            2: Instagram,
            3: Twitter,
            4: Youtube
        }

the result should be

netTeams: {
        0: {
            social: 3,
            name: 'Red',
            id: 32,
            group: 'a'
        },
        1: {
            social: 3,
            name: 'Green',
            id: 33,
            group: 'b'
        }
    }

I tried a computed property but I get errors. Any advice would be greatly appreciated!

答案1

得分: 1

以下是您要翻译的内容:

const netTeams = {
    0: {
        social: 'Twitter',
        name: 'Red',
        id: 32,
        group: 'a'
    },
    1: {
        social: 'Twitter',
        name: 'Green',
        id: 33,
        group: 'b'
    }
};

const socials = {
    1: 'Facebook',
    2: 'Instagram',
    3: 'Twitter',
    4: 'Youtube',
};
const reversedSocials = Object.keys(socials).reduce((acc, key) => {
   acc[socials[key]] = Number(key)
   return acc
}, {});
console.log(reversedSocials);

const updated = {}
for ([key, value] of Object.entries(netTeams)) {
   console.log(key)
   updated[key] = {
       ...value,
       social: reversedSocials[value.social],
   }
}

console.log(updated)

请注意,上述内容是您提供的代码部分,已经翻译成中文。

英文:

Try to run this

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const netTeams = {
    0: {
        social: &#39;Twitter&#39;,
        name: &#39;Red&#39;,
        id: 32,
        group: &#39;a&#39;
    },
    1: {
        social: &#39;Twitter&#39;,
        name: &#39;Green&#39;,
        id: 33,
        group: &#39;b&#39;
    }
};

const socials = {
            1: &#39;Facebook&#39;,
            2: &#39;Instagram&#39;,
            3: &#39;Twitter&#39;,
            4: &#39;Youtube&#39;,
        };
const reversedSocials = Object.keys(socials).reduce((acc, key) =&gt; {
   acc[socials[key]] = Number(key)
   return acc
}, {});
console.log(reversedSocials);

const updated = {}
for ([key, value] of Object.entries(netTeams)) {
   console.log(key)
   updated[key] = {
       ...value,
       social: reversedSocials[value.social],
   }
}

console.log(updated)

<!-- end snippet -->

答案2

得分: 1

首先,这与Vue.js无关,而是一个纯粹的JavaScript问题。

要执行您所需的操作,您需要:

  1. 遍历您的团队以找到每个团队的值。
  2. 通过比较团队名称与社交数组的值(按索引查找或获取对象键)来找到正确的值。
  3. 返回一个带有您找到的新“social”值的团队副本。
  4. 将所有内容包装在计算属性中,以便在netTeams更改时具有反应性。

查看以下代码段以获取完整代码。

// 如评论所示,如果您可以将基于索引的对象转换为实际数组(例如`['Facebook', 'Twitter']`而不是`{0: 'Facebook', 1: 'Twitter'}`),代码会更简单。

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->
<html>
<div id="app">
  <pre>{{ socialsWithIndex }}</pre>
</div>

<!-- 不要忘记从CDN中包含Vue -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script>
  new Vue({
    el: '#app',
    data() {
      return {
        socials: {
          1: 'Facebook',
          2: 'Twitter',
          3: 'LinkedIn',
        },
        netTeams: {
            0: {
                social: 'Twitter',
                name: 'Red',
                id: 32,
                group: 'a'
            },
            1: {
                social: 'Twitter',
                name: 'Green',
                id: 33,
                group: 'b'
            },
            2: {
                social: 'Facebook',
                name: 'Blue',
                id: 34,
                group: 'c'
            }
        }
      }
    },
    computed: {
      socialsWithIndex() {
        // 转换每个团队(必须转换为数组)
        return Object.values(this.netTeams).map(team => {
          // 从值中查找社交的索引。将其拆分为条目以获取键和值
          const [correspondingSocialIndex,] = Object.entries(this.socials).find(([socialIndex, socialName]) => socialName === team.social)

          /* 如果您的对象键始终是索引,这也可以工作
           * const correspondingSocialIndex = Object.values(this.socials).findIndex(socialName => socialName === team.social)
           */

          // 返回具有新值的“social”键的团队副本
          return {
            ...team,
            social: parseInt(correspondingSocialIndex, 10) // 将字符串键转换为数字
          }
        })
      }
    },
  });
</script>
</html>

<!-- end snippet -->

以上是代码的翻译部分。

英文:

First of all, this is not Vuejs related but a pure javascript question.

To do what you need, you have to:

  1. Iterate over your teams to find the set the value for each team
  2. Find the correct value by comparing the team name to the socials array values (find by index or get the object key)
  3. Return a copy of the team, with the new "social" value you found
  4. Wrap everything in a computed property so it's reactive when netTeams changes.

See the following snippet for the full code.

> As commented, the code would have been simplier if you could convert your index based objects to actual arrays (i.e. [&#39;Facebook&#39;, &#39;Twitter&#39;] instead of {0: &#39;Facebook&#39;, 1: &#39;Twitter&#39;}).

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;html&gt;
&lt;div id=&quot;app&quot;&gt;
&lt;pre&gt;{{ socialsWithIndex }}&lt;/pre&gt;
&lt;/div&gt;
&lt;!-- Don&#39;t forget to include Vue from CDN! --&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
new Vue({
el: &#39;#app&#39;,
data() {
return {
socials: {
1: &#39;Facebook&#39;,
2: &#39;Twitter&#39;,
3: &#39;LinkedIn&#39;,
},
netTeams: {
0: {
social: &#39;Twitter&#39;,
name: &#39;Red&#39;,
id: 32,
group: &#39;a&#39;
},
1: {
social: &#39;Twitter&#39;,
name: &#39;Green&#39;,
id: 33,
group: &#39;b&#39;
},
2: {
social: &#39;Facebook&#39;,
name: &#39;Blue&#39;,
id: 34,
group: &#39;c&#39;
}
}
}
},
computed: {
socialsWithIndex() {
// Transform each team (had to convert to an array)
return Object.values(this.netTeams).map(team =&gt; {
// Find the socials index from the value. Split into entries to get both key + value
const [correspondingSocialIndex,] = Object.entries(this.socials).find(([socialIndex, socialName]) =&gt; socialName === team.social)
/* This could work too, if your object keys are always indexes
* const correspondingSocialIndex = Object.values(this.socials).findIndex(socialName =&gt; socialName === team.social)
*/
// Return a copy of the team, with just the &quot;social&quot; key with the new value
return {
...team,
social: parseInt(correspondingSocialIndex, 10) // Convert the string key to number
}
})
}
},
});
&lt;/script&gt;
&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月8日 15:55:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定