What is the process for swapping one object for another within an array?

Is there a way in vue.js to substitute the social key in the array with another object's key that has a matching value? For instance:

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 desired output would be:

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

I attempted using a computed property, but encountered errors. Any suggestions or tips would be highly appreciated!

Answer №1

Before we dive in, it's important to note that this question pertains more to pure JavaScript rather than Vue.js.

In order to achieve your goal, you'll need to follow these steps:

  1. Go through each team and assign the appropriate value for each team
  2. Determine the correct value by matching the team name with the values in the socials array (using either index or object key)
  3. Create a duplicate of the team with the newly discovered "social" value
  4. Encapsulate everything within a computed property to ensure reactivity when netTeams undergoes changes.

Refer to the code snippet below for the complete implementation.

It would have been simpler if you could convert your index-based objects into actual arrays (e.g., ['Facebook', 'Twitter'] instead of {0: 'Facebook', 1: 'Twitter'}).

<html>
<div id="app">
  <pre>{{ socialsWithIndex }}</pre>
</div>

<!-- Ensure Vue is included from CDN! -->
<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() {
        // Iterate over each team (after converting to an array)
        return Object.values(this.netTeams).map(team => {
          // Retrieve the socials index using the value. Split into entries to access both key and value
          const [correspondingSocialIndex,] = Object.entries(this.socials).find(([socialIndex, socialName]) => socialName === team.social)

          /* Alternatively, you can use this approach if your object keys are always indexes
           * const correspondingSocialIndex = Object.values(this.socials).findIndex(socialName => socialName === team.social)
           */

          // Create a new team copy with the updated "social" key value
          return {
            ...team,
            social: parseInt(correspondingSocialIndex, 10) // Convert the string key to a number
          }
        })
      }
    },
  });
</script>
</html>

Answer №2

Give this code a try and see the results

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

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

const updatedData = {}
for ([key, value] of Object.entries(teamsData)) {
   console.log(key)
   updatedData[key] = {
       ...value,
       platform: reversedPlatforms[value.platform],
   }
}

console.log(updatedData)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhanced compatibility with Touch.radiusX feature on smartphone and tablet devices

Curious if anyone knows about the level of support for this property. I am currently using the PR0C0D1N6 app on an iPhone 4 and based on the specifications, when radiusX is not supported it should default to 1. However, in my case, radiusX is showing as un ...

Customizing style with state using react and styled-components

As a newcomer to react and styled-components, I find myself in a bit of a mess due to my lack of understanding of how it all functions. Let's start from the beginning. I have a basic page (App.js) that displays two components called "Knobs". Each &ap ...

What is the process for specifying the type for the createApp(App) function in Vue.js 3?

I'm currently working with Vue3 and Firebase using TypeScript. // main.ts import { createApp } from 'vue' import App from './App.vue' import './registerServiceWorker' import router from './router' import store f ...

Can you explain the distinction between bodyparser.urlencoded and bodyparser.json?

I'm a bit confused about the use of bodyparser. Why is it necessary when we can simply use json.stringify (to convert an object to a string) and json.parse (to convert JSON to an object)? Is it because by using app.use() with bodyparser, the middlewa ...

Are there equivalent npm variables like (`npm_config_`) available in yarn console scripts?

Utilizing variables in custom npm commands is possible (example taken from ): { "scripts": { "demo": "echo \"Hello $npm_config_first $npm_config_last\"" } } Can this functionality also be achieved ...

Is there a way to eliminate the auto-opening feature of WordPress Shortcode Ultimate Accordion on mobile devices with the help of jquery

Currently, I am utilizing the Accordion feature of Wordpress Shortcode Ultimate plugin. Although the plugin does offer an option to open the accordion on page load, I would like to have them closed by default on mobile devices. How can I achieve this usin ...

invoking a JavaScript function from an HTML file

I want to create a JavaScript server on Raspbian that not only serves .html content to the browser but also allows for user input through events like button clicks. Both my .html and .js files are located in the same directory, and I have used absolute pat ...

Tips for matching variable content with button identification to display content within a variable for ThreeJS?

I'm currently working on a project using Three.js where I need to load multiple 3D models and store them in an array. Each model has a corresponding button with a unique ID that when clicked, should add that specific model to the scene and remove any ...

Add a new row to the table when a dropdown option is selected, and remove the row when deleted. Ensure that the row is only added

Here is my specific requirement: I need a table with a default row containing a dropdown menu in the first column. When an option is selected from the dropdown, a new table row should be added with the same content as the main row and a delete button for ...

Retrieve orders from a designated date using Picqer

Is there a method to retrieve past orders using the picqer API that were placed a few days ago? After examining the filters on their website, it appears that direct access to past orders is not possible through the API alone. Is there a workaround for thi ...

The start "NaN" is not valid for the timeline in vis.js

Whenever I attempt to make a call, an error message pops up saying Error: Invalid start "NaN". I've looked everywhere online for a solution with no success. Below are the timeline options: timeline: { stack: true, start: new Date(), end: ...

Supabase Type Generation Not Working as Expected

Every time I try to update my typing through the cli command, I keep getting this error message without much information for me to troubleshoot. 2023/03/01 09:34:01 Recv First Byte Error: failed to retrieve generated types: {"message":"Forbi ...

Obtaining the value of a specific dynamic `<td>` element using jQuery

My page layout resembles this design (I am unable to post an image due to insufficient points, so I have it hosted elsewhere) My goal is for jQuery to identify the specific email when a user clicks on the delete button. For instance, if a user clicks on & ...

Sorting prices in descending order using Expedia API

Is there a way to arrange prices in descending order using the response.hotelList[i].lowRate? The provided code is as follows: success: function (response) { var bil = 1; var hotel_size = response.hotelList.length; $('#listD ...

Images in a horizontal dropdown selection menu

Currently, I have a traditional select dropdown that is data-bound with Angular. <select class="form-control" ng-model="category"> <option value="work">Work</option> <option value="home">Home</option> <option valu ...

When using AngularJS and Require together, there may be instances where the r.js

There seems to be a ongoing discussion about whether or not to use require.js with AngularJS, however, I have decided to implement it in my project. Currently, the project is set up and running with require, and my next step is to optimize and minify using ...

What emerging patterns can be observed in the security of client-side coding within the realm of web development

Keeping up with the constant flow of new frameworks and technologies can be overwhelming. One area that particularly interests me is client-side frameworks, such as AngularJS, Backbone, Knockout, jsviews, knockback, SPA... These are currently among the mos ...

Maximizing Database Connectivity in Azure Functions with Javascript

I'm having trouble finding clear guidelines on how to handle database connections (specifically MongoDB) in an Azure function written in JavaScript. According to a Microsoft document linked below, it's advised not to create a new connection for ...

What is the best way to operate both a Django and React server concurrently?

Is it feasible to run both Django and React.js servers simultaneously? Currently, I have to individually start the Backend server using python manage.py run server and then switch to Frontend to run npm start. I am working on a Fullstack project with sepa ...

Convert a relative path to an absolute path using the file:// protocol

When I scrape a website with similar html content, I come across the following code: <a href="/pages/1></a> In addition to this, I have access to the window.location object which contains: origin:"http://www.example.org" This allows me to ...