Steps for transforming an index into a value within an Object

const arr = [{
  "name": "Toyota"
}, {
  "name": "Renault"
}, {
  "name": "Jeep"
}]

const array_unique = (arr) => Array.from(new Set(arr));

const car = array_unique(
  arr.map((item) => item.name),
).sort();
console.log(car); // => ['Toyota', 'Renault', 'Jeep']

const car_map = Object.fromEntries(
  car.map((car, index) => [car, index]),
);
console.log(car_map); // => {Toyota: 0, Renault: 1, Jeep: 2,}

Is it possible to replace the numerical indexes like 0, 1, 2 with the car names itself:

{Toyota: Toyota, Renault: Renault, Jeep: Jeep,}

Answer №1

You should consider using both the map() and Object.fromEntries() methods in your code

const vehicles = [
  { make: "Toyota" },
  { make: "Renault" },
  { make: "Jeep" },
];

const uniqueVehicles = (arr) => Array.from(new Set(arr));

const carMakes = uniqueVehicles(vehicles.map((item) => item.make)).sort();

const carsMap = Object.fromEntries(carMakes.map((make) => [make, make]));

console.log(carsMap);

Answer №2

Let's simplify the process. Use the reduce method on the array to create a new object for each object in which the key is replaced by a computed property name derived from the object's name property.

const arr=[{name:"Toyota"},{name:"Renault"},{name:"Jeep"}];

const result = arr.reduce((acc, obj) => {
  return { ...acc, [obj.name]: obj.name };
}, {});

console.log(result);

For further information, refer to:

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

The Node/Express Rest API appears to keep directing requests to the same controller function, despite the mappings being correctly

Currently, I am in the process of developing a node/express REST API. When making requests to the following endpoints: http://localhost:5000/api/news and http://localhost:5000/api/news/?id=c5f69d56be40e3b56e55d80 I noticed that both URLs trigger the same ...

Having issues with my Bootstrap navigation dropdown - any suggestions on what I might be overlooking?

I'm having trouble getting the bootstrap dropdown and button to function properly when the menu collapses on tablet or mobile view. Below is my HTML code for the navigation: <nav class="navbar navbar-default navbar-fixed-top"> <div c ...

Unable to retrieve data from Express API using React frontend

After three weeks of struggling to fetch a JSON response from an Express API into a React App, I am reaching out for help. Despite spending over 40 hours on tutorials, I still haven't been able to make it work. While I know this might be redundant, I ...

Steps for converting TypeScript code to JavaScript using jQuery, without the need for extra libraries or frameworks like NPM

My single-page dashboard is quite basic, as it just displays weather updates and subway alerts. I usually refresh it on my local machine, and the structure looked like this: project/ index.html jquery-3.3.1.min.js script.js I decided to switch it t ...

What is the process of assigning a 2D array to a 1D array?

Utilizing the apache commons-math library for calculating regression parameters involves assigning a 2D array to a single array, as depicted in lines 2 and 3 of the figure. Interestingly, an error arises when replicating the same code: The error message r ...

Using AngularJS $resource as a "service" with flexible base URL

A custom JS library based on Angular includes various services for clients, structured like so: angular.module('Services', [ 'ngResource' ]).factory('UserService', function($resource) { return function(whatsonUserId) ...

Utilize vuex v-model to define the value of an object component

Coordinating input elements with object keys in Vuex state is my current challenge. Imagine I have this object: myObj: { foo: 1, bar: 2 } Within a component, I have a computed property set up like so: myObjVals: { get(){ return this.$store.state.myObj ...

The tooltip function is not functioning properly on Internet Explorer when the button is disabled

I have been utilizing a similar solution found at http://jsfiddle.net/cSSUA/209/ to add tooltips to disabled buttons. However, I am encountering an issue specifically in Internet Explorer (IE11). The workaround involves wrapping the button within a span: ...

Executable program contained within npm bundle

I am working on creating an npm package that can be executed as a command from the shell. I have a package.json { "name": "myapp", "version": "0.0.6", "dependencies": { "async": "", "watch": "", "node-promise": "", "rmdir": "", " ...

Mastering the implementation of owl-carousel in React.js

I'm currently working on a project that involves utilizing the react framework. My intention is to incorporate the owl-carousel, however, I've encountered issues as it fails to function properly. The following error keeps popping up: OwlCarousel ...

Ways to elegantly re-establish a websocket connection?

I've been working on a single-page application that utilizes HTTP and Websockets. When the user submits a form, I start streaming a response back to the client. Here's a snippet of the client-side code: var html = `<!DOCTYPE html> <met ...

Utilizing Google Maps API Version 3 to create interactive infoBubbles using an

Are there any recommended Google Maps v3 infoBubble examples that anyone has come across or knows of? I am interested in utilizing an array of data for this, but I'm unsure if there are any effective applications available or if it can be easily impl ...

I'm searching for a universal guidebook on creating web page layouts

After 5 years of creating webpages, I have realized that my sites tend to have a nostalgic 1995 internet vibe. Despite being a C# programmer with knowledge in HTML, JavaScript, and CSS, my design skills could use some improvement. Is there a quick referenc ...

Encountering an unrecoverable SyntaxError while trying to deploy a website on Netlify

When using commands like npm start, npm run build, and pm2 start server.js, everything runs smoothly without any errors. However, I encounter an issue when trying to deploy my project on Netlify. The Chrome console displays the error: Uncaught SyntaxError: ...

The error message "Unable to access property 'x' of undefined" is appearing in the photoswipe js

There is an error in the library when using photoswipe.min.js: "Uncaught TypeError: Cannot read property 'x' of undefined" The code for myPhotoswipe is identical to the one on the official site: var initPhotoSwipeFromDOM = function(gallerySelec ...

Creating a visually appealing chart similar to Excel can be achieved using JavaScript with a whopping 64382 lines of JSON data. No need for Chart.js or any additional tools - simply rely on JavaScript, HTML, and CSS to

I have a project that is due in just a few hours and I need to create a detailed chart using a large set of 64382 lines of JSON data. My knowledge of javascript is limited, so I am struggling to come up with ideas on how to approach this task. While I have ...

Adding roles in ReactJS: A step-by-step guide

I am looking to enhance the admin's roles upon login to enable the creation of new users. Unfortunately, I am uncertain on how to add these roles and make them functional. Below is the code I have: Login.js class Login extends Component { cons ...

Retrieving Distinct Values in CouchDB

In my database, there are documents that represent different rooms. Each room has properties like "floor" and "hotel", among others. What I need to do is fetch all the floors associated with a specific hotel from the database. Something like getAllFloorsOn ...

How can I add an active CSS class to an li element depending on the href attribute of its child <a> tag?

Looking for a way to dynamically add an 'active' class to a navigation menu item based on the current URL? Here's what I have so far: <ul class="nav sf-menu"> <li><a href="@Url.Action("Index","Home")">Home<span>& ...

Troubleshooting: CSS button animation not functioning

Attempting to create a hover animation for buttons on my webpage, I crafted the following CSS code: #B1 { margin: 50px; margin-top: 50px; margin-bottom: 50px; flex: 1 1 auto; padding: 20px; border: 2px solid #f7f7f7; text-align: center; te ...