What is the best way to create a brand new item using these characteristics?

Here is the object I'm working with:

const sampleData = [ { 
    main: 7,
    second: 2
    otherData: 'some string'
 } ]

I want to create a new object only containing specific properties, like this:

const newDataObject = {
    7: {
     second: 2
    }
  }

I attempted to solve this using .reduce(), but I'm struggling to exclude certain properties.

const newDataObject = sampleData.reduce((object, current, index) => {
  return {
    ..object, [index]: current
  };
}, {});

The resulting output is:

{ '0':
   { main: 7,
     second: 3
   } 
}

What mistake am I making?

Thank you.

Answer №1

You seem to be mixing up arrays and objects. If I am understanding correctly, it appears that you are looking for something like this:

const updatedData = data.map(item => {
  return {
    [item.primary]: {
      secondary: item.secondary
    }
  };
});

Based on the example input provided:

const data = [ { 
    primary: 7,
    secondary: 2
    additionalInfo: 'some string'
 } ];

The resulting output will look like this:

[
  {
    7: {
      secondary: 2
    }
  }
]

Additional Information based on feedback

It sounds like what you actually need here is the use of reduce method. You can try the following:

const reducedResult = data.reduce((accumulator, {primary, secondary}, index) => {
  accumulator[primary] = {secondary, index};
  return accumulator;
}, {});

When applied to your sample input, the outcome will be:

{
  '7': {
    secondary: 2,
    index: 0
  }
}

Please keep in mind, as mentioned earlier, if an object with the same primary value as a previous one is encountered, it will overwrite the prior entry.

Answer №2

To minimize me hod is invoked on an assortment. In this scenario, the array contains just one element. Therefore, '0' corresponds to the '[@index]' and your sole offspring object is associated with 'curr'

Answer №3

If you want to avoid using reduce, you can opt for forEach instead. See the example below:

let resultData = {};


data.forEach(({ primary, secondary }) => {
resultData[primary] = {secondary};
});

In this specific scenario, the resulting output would be:

resultData = {
 7: {
      secondary: 2
    }
}

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 request made in Node.js encountered an error with a status code of

I can't figure out why I keep receiving the status code 403 when running this code. My objective is to authenticate with Instagram. var request = require("request"); var options = { url:'https://www.instagram.com/accounts/login/', ...

suggestions for organizing data in an AJAX/jQuery page

Welcome to my JavaScript/Ajax webpage that also utilizes jQuery. I am facing a challenge with displaying a nested structure. Once a top level element is displayed, users should be able to click on it and reveal the levels below (which are dynamically gene ...

The npm package for @azure/storage-blob doesn't seem to play nice with the Azure Blob storage modules for IoT Edge

Currently, I am developing an edge module using Node.js to interact with Azure Blob storage modules on IoT Edge platform. To achieve this, I am following the documentation available at https://www.npmjs.com/package/@azure/storage-blob. The npm package ut ...

Updating the default color of selected text within a webpage's content

Is there a way to modify the default blue color that appears when content is selected on a webpage? I am wondering how to change this selection color to a custom color of choice. ...

Discovering user activity through rooms within SocketIO

My goal is to trigger an event when a user switches between online and offline status. The challenge arises from the fact that a user may have multiple tabs open, making it ineffective to track their connection status using on('connect') and on(& ...

Encountering an error message stating "Buffer is not defined" while working with gray-matter

Encountering an issue when trying to utilize gray-matter in Angular 9, the error message displayed is: ReferenceError: Buffer is not defined at Object.push../node_modules/gray-matter/lib/utils.js.exports.toBuffer (utils.js:32) at push../node_modul ...

Clear previously filtered items

I am currently working on implementing a search functionality using Javascript for my project, but I've hit a snag. After hiding certain items, I'm having trouble making them appear again. JSFiddle The code I have so far is as follows: $(' ...

How can I utilize a CDN for JavaScript libraries in Gulp?

As a newcomer to AngularJS and Gulp, I recently encountered an example where certain libraries are copied by Gulp from the 'node_modules' folder into a 'js/lib/angular2' directory: gulp.task('libs', function() { return gulp. ...

Is it possible for a nodejs server to handle both grpc and express servers simultaneously, or do they need to be separate servers?

I'm currently in the process of building a REST server using Node/Express. I'm curious about how to incorporate a GRPC server within the same setup. Would it be possible to run both servers on the same NodeJS instance, or is it recommended to hav ...

Is there a way to conceal the information entered into an email input field without specifying it as a password type?

`I'm facing a challenge at work where I need to mask the content of the input field like a password, but I'm unsure about the best approach. I tried replacing the last letters with "*" and it worked fine, but running into issues when trying to de ...

watchify with gulp requires two saves to update modifications

For a while now, I've been experimenting with watchify and encountering a saving issue. It appears that every time I make a change, I have to save twice for the modifications to reflect in the output. If I add new code to any JavaScript file, the ch ...

Steps for programmatically closing a Dialog Window in a showmodeldialog window

When opening the window, I follow this approach: var MyArgs = new Array(ParmA, ParmB, ParmC, ParmD, ParmE, ParmF); var leftpost = getWindow_TotalWidth() - 1000 - 100; var WinSettings1 = "dialogHeight:580px; dialogWidth:950px;edge:Raised; center:Yes; resi ...

Are you curious about the array of elements in React's carousel?

I'm currently in the process of constructing a website using React, and I have a specific challenge related to the "news" section. Within this section, I have a list of three components that represent different news items. These components are housed ...

Angular is not providing the anticipated outcome

I'm new to Angular (7) and I'm encountering an issue while trying to retrieve the status code from an HTTP request. Here's the code snippet used in a service : checkIfSymbolExists() { return this.http.get(this.url, { observe: 'res ...

Is there a way to limit the rotation of an a-camera in aframe?

One scenario could be enabling rotation around the z-axis within a range of -70 to 70 degrees, or alternatively, preventing rotation around any arbitrary axis. Thank you! ...

What could be causing the double invocation of render() in ReactNative?

I'm currently working on an app with a single screen displaying a map centered on the user's current coordinates. In my code below, I've set the latitude and longitude to null in the state of the App component. Using the componentDidMount() ...

Setting the default tab in easyTabs to be all-powerful

My ajax content is being loaded into a div-container through various navigation links, and I am using the script below to establish the defaultTab: $(document).ready( function() { $("#tab-container").easytabs({updateHash: true, defaultTab: "li:eq(3)"}); ...

Toggle between different socket.io servers for seamless connectivity

I'm looking for help with a situation where I need a socket.io client to connect to server A, disconnect, and then connect to server B. Any ideas on how I can achieve this? Thanks in advance! UPDATE: Attached below is the code snippet that's gi ...

The onClick event handler is triggered on page load instead of waiting for a click

Recently delving into React, I encountered an issue while attempting to call a function set as a prop. Take a look at my component below: class SamplesInnerLrg extends Component { playSampleAction(sample,sampleId) { console.log(sample); } ...

jQuery auto-complete feature that cannot be edited

We are experimenting with implementing a non-editable jQuery auto-complete feature. For example, when a user selects a value from the auto-complete dropdown, they should not be able to modify it. However, if they press the backspace key, the old value shou ...