Generate a new object by mapping an array to pair keys and values

I am facing a challenge with an array that contains duplicate values. I aim to transform this array into an object that only includes unique values, using the array values as both key and value.

In the example provided below, I have successfully created an object with only unique values. However, I am struggling to achieve an object format similar to:

{
  RookieTicketVariationRPS: "Rookie Ticket Variation RPS",
  VeteranTicketVariationRP: "Veteran Ticket Variation RPS",
  OpticsSeasonTicketRed: "Optics Season Ticket Red"
}

The notable differences in this desired format are:

  1. The key and value are identical,
  2. All whitespace has been removed from each string.

let arr = [
   {
      "manufacturer":"Panini",
      "brand":"Contenders",
      "variation":"Rookie Ticket Variation RPS",
   },
   {
      "manufacturer":"Panini",
      "brand":"Contenders",
      "variation":"Veteran Ticket Variation RPS",
   },
   {
      "manufacturer":"Panini",
      "brand":"Contenders",
      "variation":"Rookie Ticket Variation RPS",
   },
   {
      "manufacturer":"Panini",
      "brand":"Contenders",
      "variation":"Optics Season Ticket Red",
   }
   ]
   

   let set = [...new Set(arr.map((o) => o.variation))]

   let newarray= { ...set}

    console.log(newarray)

If anyone can offer guidance on how to achieve this specific outcome, it would be greatly appreciated.

Answer №1

To convert the variation string into an object, first remove any spaces to create the key and then utilize Object.fromEntries:

let arr = [{
    "manufacturer": "Panini",
    "brand": "Contenders",
    "variation": "Rookie Ticket Variation RPS",
  },
  {
    "manufacturer": "Panini",
    "brand": "Contenders",
    "variation": "Veteran Ticket Variation RPS",
  },
  {
    "manufacturer": "Panini",
    "brand": "Contenders",
    "variation": "Rookie Ticket Variation RPS",
  },
  {
    "manufacturer": "Panini",
    "brand": "Contenders",
    "variation": "Optics Season Ticket Red",
  }
];
const deduplicatedVariations = [...new Set(arr.map((o) => o.variation))];
const result = Object.fromEntries(
  deduplicatedVariations.map(
    str => [str.replaceAll(' ', ''), str]
  )
);
console.log(result);

Answer №2

If you're looking to enhance your coding skills, consider utilizing the .reduce method:

const items = [
   {
      "type":"Shirt",
      "color":"Blue",
      "size":"Medium",
   },
   {
      "type":"Jeans",
      "color":"Black",
      "size":"Large",
   },
   {
      "type":"Sweater",
      "color":"Red",
      "size":"Small",
   }
];

const updatedItems = items.reduce((accumulator, { type }) => {
  accumulator[type.replace(/\s/g, '')] = type;
  return accumulator;
}, {});

console.log(updatedItems);

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

Tips for sending hidden variables created dynamically with Jquery

I recently developed a dynamic table for my project. You can check out the DEMO here. The dynamic table is nested within a div called 'box' in a form. <div id="box"> </div> To save the dynamically generated data, I am using Jquery ...

Retrieving images from a PHP file using AJAX

My PHP page has links, and when a user clicks on the "gallery" link, I want the main div to display a grid of images. This is the code snippet of what I am currently attempting: let myRequest = new XMLHttpRequest(); myRequest.open("GET", "gallery.php", ...

Is it necessary for a container component to always be connected to Redux?

As I prepare to embark on a new React project, I am reflecting on my past experiences to establish guidelines for structuring the application. Here are some principles that I hold true: Redux serves as the central repository for data in the entire appli ...

Injecting jQuery into an Angular 1.5 component: Step-by-step guide

I'm eager to understand how to incorporate jQuery into a component. Take for instance Within my webpack configuration file: new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }) In the file of my component: ...

A guide on applying bold formatting to a specific section of text in React

I have a collection of phrases structured like so: [ { text: "This is a sentence." boldSubstrings: [ { offset: 5, length: 2 } ] } ] My goal is to display each phrase as a line using the following format: ...

Contrasting delete and $destroy

In my quest to understand memory leak management in angularjs, I have encountered the $destroy method. This got me thinking - given that JavaScript already has a delete keyword, is there any distinction between the two? ...

Saving a picture to local storage with the file input type in ReactJS

I am attempting to save an image in the browser storage once a user selects an image from their computer. <div className="add_grp_image_div margin_bottom"> <img src={img_upload} className="add_grp_image"/> <input type="file" class ...

Exploring the differences between single quotes and double quotes in jQuery.parseJSON

Can you explain the difference between the following code snippets? This code snippet works perfectly: var obj1 = jQuery.parseJSON('{"orderedList": "true"}'); document.write("obj1 "+ obj1.orderedList ); However, the following code snippet does ...

Does the CSV stream parser (PapaParse) cause rendering delays?

Currently, I am utilizing papa parse to fetch csv streams from my backend in order to visualize data. However, I have observed that while it is successfully invoking the callback for the data chunks, it is also causing rendering issues. I am attempting to ...

Clicking on an object will trigger the threejs to traverse through

I need to implement a wireframe for an object when a button is clicked. I am using the traverse function to achieve this, and it works perfectly fine in the OBJMTLLoader. However, when I try to use it in a separate function as shown below and then click th ...

What are the steps to implement an audio stream in a JavaScript React application?

I have been working on integrating a web dialer system into my JavaScript NextUI React app. After making some progress, I can successfully dial and hear my voice through the phone. However, I am encountering an issue where I cannot hear the other person sp ...

Setting textures for a loaded .obj file in three.js without using a .mtl file

Is it possible to apply material like THREE.MeshPhongMaterial() to a specific object within a loaded .obj file that contains multiple objects? var customMaterial = new THREE.MeshBasicMaterial( { color: 0x444444 } ); var loader = new THRE ...

Retrieving information from one controller to another controller

I have been tasked with developing an application using angularjs. The application consists of a login page and home page. The layout is divided into two sections - header and container, each controlled by headerCtrl and loginCtrl respectively. The heade ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

Increase the sum of 0 by adding long integers with a length of 9 digits in Java

At the start of the program, users are asked to input a value assigned to variable n. They are then prompted to enter long digits n times. These digits are stored in an array called ar. The goal of the function aVeryBigSum is to iterate through the numbers ...

Maintain the property characteristics (writable, configurable) following the execution of JSON.parse()

Imagine a scenario where an object is created elsewhere and passed to my module. It could have been generated on the server in node.js, or perhaps in a different module where it was then serialized using JSON.stringify() for transmission (especially if it ...

Detecting changes in arrays in Vue.js 2

Below is a simplified version of the code : <template> /* ---------------------------------------------- * Displaying a list of templates, @click to select the template /* ---------------------------------------------- <ul> ...

AngularJS directive not registering event after model update

Within my angularjs application, I have implemented an element directive that is equipped with an event listener. This listener is designed to respond to a broadcast event from the controller. app.directive('listItem', function(){ return { ...

Encountering Next.JS Router Issue: Unable to Access Properties of Null (specifically 'useContext')

As a beginner in Next.js and React, I'm facing an issue with redirecting users from the "Projects" page to the Product Page Details. Here's the code snippet I am using: const openProjectDetails = () => { Router.push('/api/' + props ...

Is it possible to include a link to an external page and execute a JavaScript function on that page simultaneously

I am attempting to link directly to an external page that displays a list of order numbers which are loaded via AJAX when clicked. The URL of the external page is http://www.example.com/orders and it uses a JavaScript function javascript:load_order('X ...