Top method for transforming an array into an object

What is the optimal method for transforming the following array using JavaScript:

const items = [
  { name: "Leon", url: "../poeple" },
  { name: "Bmw", url: "../car" }
];

into this object structure:

const result = {
  Leon: "../poeple",
  Bmw: "../car"
};

Answer №1

You have the option to simplify the array:

const items = [{
    name: "Leon",
    url: "../people"
  },
  {
    name: "Bmw",
    url: "../car"
  }
];

const o = items.reduce((o, el) => {
  o[el.name] = el.url;
  return o;
}, {});

console.log(o)

The Array.prototype.reduce function is versatile and can be utilized to condense an array into another structure:

The reduce() function applies a custom "reducer" callback operation on each element of the array, sequentially, with the previous element's calculation result. The final outcome after operating the reducer on all elements results in a singular value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Answer №2

If you assign each object as an entry and extract an object from it, you'll get the desired output.

let
    elements = [{ type: "Chair", color: "brown" }, { type: "Table", color: "white" }],
    outcome = Object.fromEntries(elements.map(({ type, color }) => [type, color]));

console.log(outcome);

Answer №3

Exploring various methods when working with JavaScript is essential. If you're just starting out with JavaScript, using a simple loop to iterate through an array and create new key-value pairs in a fresh object could be less complex.

const items=[{name:"Leon",url:"../poeple"},{name:"Bmw",url:"../car"}];

const out = {};

for (const obj of items) {
  out[obj.name] = obj.url;
}

console.log(out);

Answer №4

A different approach (successfully tried and tested with the given scenario):

const transformData = (source) => {
  let result = {};
  for (let index = 0; index < source.length; index++) {
    let item = source[index];
    result[item.title] = item.link;
  }
  return result;
}

Answer №5

Follow this Example

const elements = [
   { label: "Apple", link: "../fruits" },
   { label: "BMW", link: "../vehicles" }
];

const newObject = Object.fromEntries(elements.map(item => [item.label, item.link]));
console.log(newObject);

Alternatively, you can define a function like so

const elements = [
    { label: "Apple", link: "../fruits" },
    { label: "BMW", link: "../vehicles" }
  ];


const convertArrayToMap = (array, key) => {
const initialValue = {};
   return array.reduce((obj, data) => {
    return {
      ...obj,
      [data[key]]: data.link,
    };
  }, initialValue);
};

console.log(convertArrayToMap(elements, "label"));

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

Pass a bespoke object back to the GraphQL resolver

In my Node-Express backend server with GraphQL setup, I am working on providing a custom object as output for a GraphQL resolver. The usual Sequelize approach hasn't worked for me in this case, so I'm exploring new methods. const RootQueryType = ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...

Using ng-repeat data to populate another function

I am looking to transfer the details of an order shown in an ng-repeat to another function within my controller. Currently, it works for the first item in the array. How can I extend this functionality to display any order currently visible on the page? W ...

Im testing the creation of a global style using styled-components

Is there a way to create snapshot tests for styled-components with createGlobalStyle? The testing environment includes jest v22.4.4, styled-components v4.1.2, react v16.7, jest-styled-components v5.0.1, and react-test-renderer v16.6.3 Currently, the outp ...

If the user is not authenticated, Node.js will redirect them to the login page

I've integrated the node-login module for user login on my website. Once a user logs in, the dashboard.html page is rendered: app.get('/', function(req, res){ // Check if the user's credentials are stored in a cookie // if (req.coo ...

Browser fails to display input value when altered

I have noticed that when the value of the Input element changes, the browser does not display the updated value. However, you can verify this change by inspecting the DevTools in the browser. I am curious as to why the actual value of the Input element is ...

What is the typical response time for a request using javascript axios?

In my current application, I am fetching data from an API and everything is functioning correctly. However, I am interested in determining the duration of each request in milliseconds. To achieve this, I implemented interceptors using axios. The challenge ...

Tips on transferring key values when inputText changes in ReactJs using TypeScript

I have implemented a switch case for comparing object keys with strings in the following code snippet: import { TextField, Button } from "@material-ui/core"; import React, { Component, ReactNode } from "react"; import classes from "./Contact.module.scss" ...

The active link for pagination in CodeIgniter is malfunctioning

Even though there might be similar posts on StackOverflow, my situation is unique. Hence, I have decided to ask this question with a specific title. Let me break down my issue into smaller parts: Part - 1: I have a regular view page where I can select a ...

Can you clarify the significance of the "1" in this particular Typescript code snippet?

Can anyone provide some insight into the purpose of this '1' in the following TS code snippet? decryptPassPhrase() { this.$encrypt.setPrivateKey(privateKey); this.decryptedPassPhrase = this.$encrypt.decrypt(this.encryptedPassPhrase); ...

What could be causing the malfunction of this Bootstrap button dropdown?

Initially, I attempted using regular HTML for the dropdown button but encountered issues. As a result, I switched to jsfiddle to troubleshoot. Despite my efforts, the dropdown feature still refused to work. If you'd like to take a closer look, here&a ...

I am in the process of creating several checkboxes and am looking to incorporate some added functionality

Currently, I am working on a project that involves creating multiple checkboxes. My goal is to implement a specific functionality where only one checkbox can be checked in each group with the correct or incorrect value. Once all groups have been selected, ...

wait until the CSS parser retrieves the CSS files

I am trying to ensure that the page is rendered only after the CSS has been loaded. The function css_parser.getCSSFiles() reads the file asynchronously and sends the CSS content to the variable css.cssFile. How can I make sure that res.render waits for t ...

Using prevState in setState is not allowed by TypeScript

Currently, I am tackling the complexities of learning TypeScipt and have hit a roadblock where TS is preventing me from progressing further. To give some context, I have defined my interfaces as follows: export interface Test { id: number; date: Date; ...

Equal size images displayed within cards in Material UI

Is there a way to create a list of Material UI components with images that have uniform height, even if the original images vary in size? I want to make all image heights responsive and consistent across all cards. Any suggestions on how to achieve this? ...

Passing an empty JSON object through Ajax requests

To Whom it May Concern (I am simply attempting to meet the "please add more detail" requirement) Upon sending data to the server as shown below, the body appears empty. Server // Route for POST method app.post('/pass', function (req, res) { ...

There is a random section that keeps crashing on the website

I have encountered a bug on my one-page Bootstrap template website. One of the sections is causing issues after multiple page refreshes. Despite checking the console for errors, I am unable to identify the source of the problem. Here is the HTML code for ...

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...

Having trouble retrieving the ng-model value from input in the controller

I am new to Angularjs and I am working with a datepicker in Ionic. After selecting a date, the input field is correctly getting the value of the selected date. However, I am facing an issue when trying to access this value in the Controller using $scope. ...

Creating valuable properties in TypeScript is a skill that requires knowledge and practice

In TypeScript, there is a unique feature available for defining properties with values using the `value` keyword. class Test { constructor(private value: number = 123) { } public MyValueProperty: number = 5; } Here is how you can define such ...