Use Javascript to generate an object with keys based on values from an array

In my project, I am working on a method that is responsible for returning a user object based on the provided id. The challenge here is that this method needs to be adaptable for future use cases and cannot simply rely on the current structure.

The database I am working with has a key called type, which allows me to filter out a collection of users. My task is to create an object where each user's _id serves as the key, while excluding the _id and type from the user object.

I aim to leverage tools like lodash or ES6 features to transform an Array like:

[
  {
    "_id": "0e12e661cb50068a135b36067f001d20",
    "name": "Joe Bloggs",
    "type": "user"
  },
  {
    "_id": "0e12e661cb50068a135b36067f00373f",
    "name": "Ben Bloggs",
    "type": "user"
  }
]

Into an Object structured as follows, omitting the _id and type:

{
  "0e12e661cb50068a135b36067f001d20": {
    "name": "Joe Bloggs"
  },
  "0e12e661cb50068a135b36067f00373f": {
    "name": "Ben Bloggs"
  }
}

UPDATE: It's crucial for me to return the entire object rather than just the name, as additional properties may be added to these objects in the future.

Answer №1

If you want to achieve this, you can simply utilize the reduce() method.

var info = [{
  "_id": "0e12e661cb50068a135b36067f001d20",
  "name": "Joe Bloggs",
  "type": "user"
}, {
  "_id": "0e12e661cb50068a135b36067f00373f",
  "name": "Ben Bloggs",
  "type": "user"
}]

var result = info.reduce(function(r, e) {
  r[e._id] = {name: e.name};
  return r;
}, {})

console.log(result)

An ES6 version using an arrow function

var result = data.reduce((r, e) => (r[e._id] = {name: e.name}, r), {})

Update: If you only need to exclude specific properties from a new object, you can employ Object.assign() DEMO to duplicate the object and then use delete to eliminate certain properties. Alternatively, you can utilize a forEach() loop to add desired properties DEMO

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

glitch discovered in the validation process of phone numbers

I've been working on a phone number validation code where I need to verify if the input is numeric. Below is the code snippet that I have been using: var phoneres; function checkphone(num) { var filter = /^[0-9]{3}\-[0-9]{7}$/; if (filt ...

Express JS: Condition to pause execution for 50 seconds until receiving the firestore query response, otherwise proceed with the other process

I am working on a project to create a simple application that will wait for 50 seconds for an API or database call. If it does not receive a response within the specified timeframe, it will discard the call and move on to the next one. async (collection, d ...

A guide on extracting specific text from a div class

<div class="col_5"> <br> <i class="phone"> :: Before </i> 0212 / 897645 <br> <i class="print"> ...

I am experiencing difficulty with Three.js rendering textures from my planet constructor function

I am facing an issue with my function that is supposed to create a 3D object (a planet) using orbital parameters and texture images from a dataset. Strangely, the textures are not rendering when I use StandardMaterial or PhongMaterial, even though they wor ...

How can you use JavaScript and regex to extract the word before a comma?

Hey there, I'm attempting to extract the word right before a comma in a sentence. For instance, consider the following string: "Cloudy, and 51 ° F " I aim to retrieve CLOUDY as the output. Could someone guide me on how to achieve this using regex ...

Ensuring that undefined is not present before making an API request is crucial in the componentWillMount lifecycle

When I have a component that triggers methods depending on asynchronous API requests, I check certain props using componentWillmount. If a specific prop is true, I trigger a function; otherwise, I do not. The issue arises when the prop is initially undef ...

Filter Vue.js dropdown by checking if a word is present in the array (partial match only)

https://jsfiddle.net/75f3c2po/ Is there a way to modify the Vue.js code above so that it filters by dropdown to match the entire array even if there are commas separating other words? Currently, it only matches if the type: BMW, but I would like it to als ...

Sharing the logger object in NodeJS projects: What's the best approach?

After setting up a logger object in the file utils/logger.js using the winston package, I am wondering how to propagate this logger object to all project files (approximately 20 in total). Do I need to include const logger = require('../utils/logger&a ...

JS, Express: Encounter issues - unable to find view in directory despite following provided instructions

Currently, I am following the steps outlined in this guide: Despite conducting extensive research, I am facing difficulty in getting it to work as expected. Here is the folder structure I am working with: https://i.sstatic.net/jCEdO.png Below is a snipp ...

The type 'number[]' is lacking the properties 0, 1, 2, and 3 found in the type '[number, number, number, number]'

type spacing = [number, number, number, number] interface ISpacingProps { defaultValue?: spacing className?: string disabled?: boolean min?: number max?: number onChange?: (value: number | string) => void } interface IFieldState { value: ...

Issue with Mobile NavBar remaining visible after clicking on target element in HTML CSS

On my website, everything works perfectly with the Nav bar except for when I am on mobile. When I click on any href from my Nav Bar, it directs me to the correct location but does not close the Nav Bar afterward. I need it to function this way: After click ...

Using values from a designated line within the textarea to successfully submit a GET form

How can I extract values from a specific line in a TextArea and use them to submit a form? <!DOCTYPE html> <html> <body> <input type='button' value='submit' onclick='document.getElementById("submit-line-3") . ...

Get a specific value from a JSON object

Within my Calendar, there is a code snippet that includes an Object and JSON data. This JSON object contains various properties such as [{"Date":"17-3-2015","Event":"Test drive","Participants":"John, George","Description":"Testing a new F30"}, {"Da ...

Exporting routes in Node.js and Express - A step-by-step guide

I am experiencing an issue that is not entirely related to the question, but rather to the same page. After exporting a route to my main app.js file, my post route is not functioning. Below are the problems I am facing, which require you to read the code t ...

Retrieve the parameter values in PHP that were passed from AngularJS

This is my first time working with PHP and AngularJS. I am trying to pass parameters from AngularJS to a PHP file, where they will be used in an INSERT query. I have set up an XMLHttpRequest to call the PHP file (addsubscriber.php?par1=val1&par2=val2) ...

Ways to determine the existence of five consecutively increasing values in a vector

I have a vector and I'm trying to determine if there are any sequences of five consecutive numbers where the values are in increasing order (sorted). While I've come up with a solution, I believe that there is likely another more efficient approa ...

Avoid rendering the React component until the AJAX call has completed

Suppose the following code is given: componentDidMount() { $.ajax({ type: 'GET', url: '/data/', dataType: 'text', success: function(response) { this.setState({data: response}) ...

Is it possible to use the column (PK) as an index in the resulting array when using 'mysqli_fetch_all'?

My current code snippet looks something like this: <?php // ...More Code $result = mysqli_query($mysqli, "SELECT * FROM stock_types"); if(!$result || mysqli_num_rows($result) < 1) die('error'); $stock_types = mysqli_fetch_all($re ...

Toggle Form Section Visibility

I am working on a table with five rows that have upload buttons. Each time I submit a row, the page refreshes, but I want to hide all but one row at a time. When the first submit button is clicked, it should show the next row and hide the previous ones. Th ...

Receiving HTML from NodeJs instead of JSON

I am currently working on a project that involves developing an app and landing pages. While we are using NodeJs with Axios and VueJs for the app part, the landing pages are built using simple jQuery. I need to make API calls for the landing pages, but I a ...