An effective method to utilize .map and .reduce for object manipulation resulting in a newly modified map

Here's an example of what the object looks like:

informations = {
    addresses: {
        0: {phone: 0},
        1: {phone: 1},
        2: {phone: 2},
        3: {phone: 3},
        4: {phone: 4},
        5: {phone: 5},
    },

    names: {
        0: n0,
        1: n1,
        2: n2,
        3: n3,
        4: n4,
        5: n5,
    }
}

How can I obtain the result in this format:

[{phone: 0, name: n0}, {phone:1, name: n1} .....{phone:5, name: n5}]
?

I tried using .map, but it gave me an error stating "Property 'map' does not exist on type".

Is there a more efficient way to write the code without resorting to a for() loop?

Answer №1

map as well as reduce are functions exclusively meant for arrays, not objects. If you want to loop through an object without restructuring it into an array first, the appropriate method to use is for...in. However, if converting the object into an array is acceptable, there are other ways to achieve iteration such as using Object.entries, keys, or values, followed by operations like reduce, map, forEach, or for...of.

In this particular scenario, the data appears to be in a peculiar arrangement where objects with incrementing integer keys are being misused as arrays. To rectify this, you can transform these objects into arrays by utilizing Object.values, and then consolidating the two arrays together using a method similar to Python's "zip" functionality but implemented with the help of map (assuming both arrays are of equal length):

const informations = { addresses: { 0: {phone: 0}, 1: {phone: 1}, 2: {phone: 2}, 3: {phone: 3}, 4: {phone: 4}, 5: {phone: 5}, }, names: { 0: "n0", 1: "n1", 2: "n2", 3: "n3", 4: "n4", 5: "n5", } }

const addresses = Object.values(informations.addresses);
const names = Object.values(informations.names);
const result = addresses.map(({phone}, i) => ({
  phone, name: names[i]
}));
console.log(result);

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

Error message: "Encountered a template parsing error stating that the element 'ngb-carousel' is not recognized."

Initially, I created a fresh project using the Angular CLI by running this command: ng new my-project Next, I followed the instructions in the angular-cli readme to install Bootstrap 4. After that, I installed NG Bootstrap. Then, I generated a new comp ...

Tips for making a React/Socket.IO app accessible from external sources

Trying to get my React app (built with Node.js and Socket.IO) running locally and accessible from external sources has been a challenge for me. I've managed to expose port 3000 using ngrok tunneling, but my socket connection is listening on port 3001. ...

Using the "i" parameter in a Lodash for loop results in undefined, however, it functions properly with specific values set

My goal is to use Lodash to search for specific integer values in an object and then store some of those values in an array. The integers are variable and come from a separate array, but I am consistently getting undefined as the result. If I manually inp ...

Refreshing the current window with the ``Window.location.reload()`` function

I have integrated a map that displays clients using markers. The map I am utilizing is Leaflet with an AngularJS directive. The issue I am facing is that when I initially access the map, it functions correctly. However, when I change routes, all the marke ...

Leverage the child interface as a property interface containing a generic interface

I'm facing an issue while trying to incorporate typings in React. The concept is centered around having an enum (EBreakpoint) that correlates with each device we support. A proxy wrapper component accepts each device as a prop, and then processes the ...

Angular2 Cache: Enhance Your Application's Performance

Currently seeking a cache solution for my Angular2 application. Imagine we have a massive collection of Movie objects stored on a server, too many to fetch all at once. The server offers a REST endpoint: getMovie(String id) On the client side, I need a s ...

Obtaining an array through an AJAX request in JavaScript

I'm struggling with my ajax call setup: request = new XMLHttpRequest(); request.open("GET","/showChamps?textInput=" + searchChamp.value,true); request.send(null); request.onreadystatechange = function () { if (request.status == 200 && reques ...

Creating personalized mapping for TypeScript objects

I have a TypeScript object structure that resembles the following: { "obj1" : { object: type1;}; "obj2" : { object: type2;}; "obj3" : { object: type3;}; "obj4" : { object: type4;}; "obj5" ...

Error in Typescript: The element is implicitly assigned an 'any' type due to the inability to use a 'string' type expression as an index

I'm a beginner with TypeScript and I encountered an error that's confusing to me while trying to follow an online tutorial on sorting data in Reactjs using React hooks. Here is the section of my component code where the error occurs: Element imp ...

What is the specific character code assigned to the "Enter" key on a

Check out this code snippet: http://jsfiddle.net/YttKb/ In my javascript, I am trying to add a new line of text using utf-8 coding. Which character should I use to make a new line? It seems like \n only creates a line break, not a new line of text. ...

What is the best way to save Vue state in a cookie while transitioning between form steps in a Laravel application

Imagine a scenario where a user is filling out a multi-step form, and we want to ensure that their progress is saved in case they lose connection. This way, the user's data will not be lost between different form steps. In addition to saving each ste ...

Communication between the Node development server and the Spring Boot application was hindered by a Cross-Origin Request

Here is the breakdown of my current setup: Backend: Utilizing Spring Boot (Java) with an endpoint at :8088 Frontend: Running Vue on a Node development server exposed at :8080 On the frontend, I have reconfigured axios in a file named http-common.js to s ...

Alter the background color of a div contingent on the checkbox being checked within

I am in search of a solution to modify the background color of a parent div that contains a checkbox. The condition is that the background color should only change when the 'checked' attribute is present within the tag. HTML <div class="comp ...

The TypeScript compiler is unable to locate the name 'window'

Within my Meteor/React project, I encounter the following line of code: let gameId = window.prompt("Please input the ID of the game you would like to load."); The TypeScript compiler presents an error during transpiling: Cannot find name 'window&apo ...

Error encountered while attempting to validate and add new entries

I am facing a challenge while attempting to insert a record into my mongodb database. Despite providing what seems to be the correct values, mongoose is flagging them as missing. Below is the Schema I am working with - var mongoose = require('mongoo ...

Material-inspired Design Device Compatible DIV slide with JS, JQuery, and CSS

My goal is to achieve something similar to this: Desired Live Website I am looking for a feature where clicking on the div will slide in content from the right, load an external page inside it, and close when prompted. The slider div should be device c ...

Creating a blank webpage after including a component tag for an Angular form

I encountered an issue while developing an Angular form. It seems that using the app-name-editor tag causes my entire HTML page to go blank, and the form does not display. However, removing the tag restores the webpage's functionality. This leads me t ...

Uncaught TypeError: Cannot create new instances of User - Node.js server not recognizing User as a constructor

I encountered an issue while attempting to save a user to MongoDB database using a post request. The error message "TypeError: User is not a constructor" keeps popping up despite the straightforward setup of my code. I have double-checked but can't se ...

Maintain the value of `this` using a recursive setImmediate() function

Hey there! I'm working on a node.js app where I need to utilize setImmediate() to recursively call a function while maintaining its context for the next iteration. Let's take a look at an example: var i=3; function myFunc(){ console.log(i ...

Bootstrap 4 experiences issues with modal dialogs

I am experiencing an issue with my code not working on Bootstrap 4. When I click on the 'overview' button, the page darkens but the dialog does not appear. This functionality worked fine with the old version of Bootstrap. Can someone please assis ...