What is the best way to divide a single-item object array into three separate objects?

Here is the data structure for the response data:

const res = {
  data: [{
    name: 'c2',
    ipaddr: '192.168.1.5',
    port: 4435,
    sshuser: "abc",
    sshpass: "xyz",
    sshport: 22,
    license: 'license.txt',
  }],
};

I need to transform it into the following format:

const newState = [{
  name: 'c2',
  ipaddr: '192.168.1.5',
  port: 4435,
}, {
  sshuser: "abc",
  sshpass: "xyz",
  sshport: 22,
}, {
  license: 'license.txt',
}]

The code below successfully achieves the desired outcome:

const newState = [{name: res.data[0].name, ipaddr: res.data[0].ipaddr, port: res.data[0].port},{sshuser: res.data[0].sshuser, sshpass: res.data[0].sshpass, sshport: res.data[0].sshport},{license: res.data[0].license}];

Are there alternative methods to achieve the same result, perhaps with a more concise syntax?

Answer №1

Great job on your code! It's functional and effective, although I would recommend using const instead of var. Another approach you could consider is using mapping, especially if your original array contains multiple objects. In that case, you might want to explore using .map() instead of .flatMap():

const res = {data: [ {name: 'c2', ipaddr: '192.168.1.5', port: 4435, sshuser: "abc", sshpass: "xyz", sshport: 22, license: 'license.txt'}]};

const newState = res.data.flatMap(({name, ipaddr, port, sshuser, sshpass, sshport, license}) => [
  {name, ipaddr, port}, {sshuser, sshpass, sshport}, {license}
]);

console.log(newState);

Another option is to use object destructuring on your array objects and utilize shorthand property names to create the array of objects:

const res = {data: [ {name: 'c2', ipaddr: '192.168.1.5', port: 4435, sshuser: "abc", sshpass: "xyz", sshport: 22, license: 'license.txt'}]};

const [{name, ipaddr, port, sshuser, sshpass, sshport, license}] = res.data;
const newState = [{name, ipaddr, port}, {sshuser, sshpass, sshport}, {license}];
console.log(newState);

Answer №2

No issues arise in the method used to obtain the result in the OP's code example.

An approach centered on object-destructuring and shorthand property-names could be represented by the following code snippet ...

const {
  name, ipaddr, port,
  sshuser, sshpass, sshport,
  license,
} = res.data[0];

const newState = [
  { name, ipaddr, port },
  { sshuser, sshpass, sshport },
  { license },
];
console.log('newState ...', newState);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script>
  const res = {
    data: [{
      name: 'c2',
      ipaddr: '192.168.1.5',
      port: 4435,
      sshuser: "abc",
      sshpass: "xyz",
      sshport: 22,
      license: 'license.txt',
    }],
  };
</script>

Answer №3

Your problem-solving approach is always influenced by the underlying goal you want to achieve.

^ Opting for a concise solution may not always be the best choice.

Remember, the length of your code does not always dictate its quality. Code readability is crucial.

If your goal involves transforming an object into an array of objects where each object comprises a selected set of keys from the original object, you can implement a function tailored for this purpose. This function can be reused for varying objects, even those with distinct keys. Here's a sample implementation:

function selectKeys(input, keys) {
  const result = {};
  for (const k of keys) result[k] = input[k];
  return result;
}

function groupKeys(obj, groups) {
  return groups.map((keys) => selectKeys(obj, keys));
}

const data = {
  example: [{
    property1: "value1",
    property2: "value2",
    property3: 123,
    property4: "abc",
  }],
};

const actualResult = groupKeys(
  // Source object
  data.example[0],
  // Keys for each object in the resulting array
  [
    ["property1", "property2", "property3"],
    ["property4"],
  ],
);

const expectedResult = [{
  property1: "value1",
  property2: "value2",
  property3: 123,
}, {
  property4: "abc",
}];

console.log(JSON.stringify(actualResult) === JSON.stringify(expectedResult)); // true

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

Imagine a complex JSON structure with multiple levels of nesting

Take a look at this JSON data : { department_1 : [{ id : 1, name = Joe Smith, email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660c150b0f120e2613150048030213">[email protected]</a>}, ...., { id : 500, name ...

Calculate the value of x to the power of k, where both x and k are arrays of any dimension

I have two numpy arrays: Array x has dimensions (n, a0, a1, ...), while array k has dimensions (n, b0, b1, ...). My goal is to calculate an array of exponentials such that the resulting output will have dimensions (a0, a1, ..., b0, b1, ...). out[i0, i1, ...

Tips for containing a range slider within a div element in a flexbox container

I am currently using Javascript to generate a grid of images, and I want to include a range slider at the bottom of one of the images. Here is a simplified version of my code using flex-container: <style> .flex-container { display: flex; fle ...

What is the best way to capture the inputs' values and store them accurately in my object within localStorage?

Is there a more efficient way to get all the input values ​​and place them in the appropriate location in my object (localStorage) without having to individually retrieve them as shown in the code below? Below is the function I currently use to update ...

Vue.js encountered an error: Unexpected TypeError in promise. The function $set is not recognized

Currently, I am working on fetching comments from the Reddit API and attempting to update an array using $set in order to refresh the view. However, I encountered an error: Uncaught (in promise) TypeError: $set is not a function Virtual Machine Component ...

What could be the issue with my interactive dropdown menu?

I am currently experiencing an issue with a drop down list that is supposed to fetch records from a column in another table, but no records are appearing. Additionally, I would like to add an option in the drop down list labeled "others" for users to inp ...

Exclude a specific link from a JQuery function

Check out this unique single page site that utilizes a waypoint script for navigation and highlighting nav items - The functionality works seamlessly, however, we are facing an issue where we need to modify a link to redirect to an external website. Unfor ...

Component's state not reflecting changes after dispatching actions in Redux, though the changes are visible in the Redux DevTools

When a menu item is clicked, I execute the following code: import React, { Component } from 'react'; import 'react-dropdown-tree-select/dist/styles.css'; import { connect } from 'react-redux'; import '../../../css/tree.c ...

Instructions on activating the standard scrolling function for a specific DIV element

I'm struggling to achieve a specific scrolling effect on my one-page website. I want the initial section to be displayed as a full page, and when the user scrolls down, it should transition to the next section with a full page scroll. However, once th ...

What could be causing the incorrect updating of React State when passing my function to useState?

Currently, I am in the process of implementing a feature to toggle checkboxes and have encountered two inquiries. I have a checkbox component as well as a parent component responsible for managing the checkboxes' behavior. The issue arises when utiliz ...

Karma is unable to locate the module within the specified relative path

I'm facing a challenge with Karma not being able to load a specific file. As a novice in Karma, I dedicated the entire day to researching and checking documentation for similar issues with no luck. Upon initiating the karma process, it encounters an ...

Sending a property as a parameter to a different component through Vue's router-link

I have a component designed to showcase recipes in a list format. Each recipe is rendered using a separate component from an array of recipes. I am currently attempting to pass the recipe object from one component to another component using Router-Link ...

50% greater than the highest of the other values

I'm a beginner when it comes to JavaScript and I need help setting a maximum value of 50% of the selling price. Can someone offer guidance? The fields I have are called "sale_price" and "discount". click here for image description What is the best ...

Error in NodeJS: 'Cannot alter headers once they have been sent.'

My project involves developing an app with Express that fetches tweets from Twitter. Each API call retrieves 200 tweets (or fewer if there are less than 200) and in total, I need to retrieve 1800 tweets. To achieve this, I use a time interval to make multi ...

"Enhance User Interaction with a Bootstrap Popup when Submitting Form Data via

As a junior web master, I have a simple question to ask. I have created a single page application for a client with a contact form at the end of the page. The validation is done using Bootstrap, but the only method I know to send the form data to a mail id ...

The javascript function ceases to operate once the div is refreshed

$(function() { $(".reqdeb").click(function() { console.log("Functioning properly"); var req_id = $(this).attr("id"); var info = 'id=' + req_id; if (confirm("Confirm deletion of request?")) { $.ajax({ cache : false, ...

Clearing LocalStorage and Cache upon initial loading in Next.js

Our project requires continuous updates, and currently users are required to manually clear their cache and localStorage data after each update in order to access the new features. Is there a solution to automatically clear all cached data upon user visi ...

Iterate through each image within a specific div element and showcase the images with a blur effect applied

I have a div with multiple images like this: <div class="am-container" id="am-container"> <a href="#"><img src="images/1.jpg"></img></a> <a href="#"><img src="images/2.jpg"></img>< ...

Webpack configuration for asynchronous loading

I'm having trouble making this work. Can someone please assist? :) (According to the documentation, webpack is capable of handling Promises) Here is what works for me: var compiler = webpack(webpackConfig) However, when I try using a promise, I en ...

utilize jquery ajax to input various data

I am attempting to include multiple data in a jQuery ajax call. However, my current implementation is not working as expected. The data fetched is taken from the following span: <span id="<?php echo $tutorial_id; ?>" modes="<?php echo $modese ...