Converting an Array of Strings into Objects

I need to convert an array of strings, each with comma separated values, into an array of objects.

Here is an example:

var myarray = [
 "a1,b1,c1,d1",
 "a2,b2,c2,d2",
 "a3,b3,c3,d3"
]

This should be transformed into:

[
  {
    "field1": "a1",
    "field2": "b1",
    "field3": "c1",
    "field4": "d1"
  },
  {
    "field1": "a2",
    "field2": "b2",
    "field3": "c2",
    "field4": "d2"
  },
  {
    "field1": "a3",
    "field2": "b3",
    "field3": "c3",
    "field4": "d3"
  }
]

I have experimented with different methods like using Object.assign and the spread operator. However, I believe there might be a more straightforward solution involving destructuring or another technique.

Answer №1

var myarray = [
 "a1,b1,c1,d1",
 "a2,b2,c2,d2",
 "a3,b3,c3,d3"
];

const convertToProperties = arr => arr.map(item => item.split(',').reduce((result, splitItem, index) => {
  result['field' + (index + 1)] = splitItem;
  return result;
}, {}));

console.log(convertToProperties(myarray));

Experience a demonstration showcasing the use of words instead of numbers

var myarray = [
 "a1,b1,c1,d1",
 "a2,b2,c2,d2",
 "a3,b3,c3,d3"
];

const numbers = ['one', 'two', 'three', 'four'];

const convertToProperties = arr => arr.map(item => item.split(',').reduce((result, splitItem, index) => {
  result[numbers[index]] = splitItem;
  return result;
}, {}));

console.log(convertToProperties(myarray));

Answer №2

To create a custom mapping function that transforms an array into objects with specific properties, you can first map the array values and then assign them to new properties in a new object.

var myarray = ["a1,b1,c1,d1", "a2,b2,c2,d2", "a3,b3,c3,d3"];

const fromArrayToObjects = (array) =>
  array.map((value, index) => {
    const o = Object.assign({}, value.split(","));
    Object.keys(o).map((key, i) => {
      Object.defineProperty(
        o,
        "field" + (i + 1),
        Object.getOwnPropertyDescriptor(o, key)
      );
      delete o[key];
    });
    return o;
  });
console.log(fromArrayToObjects(myarray));

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

Exploring the Depths of Javascript Variable Scope

bar: function () { var cValue = false; car(4, function () { cValue = true; if (cValue) alert("cvalue is true 1"); }); if (cValue) alert("cvalue is true 2"); } car: function (val, fn) { fn(); } I have encountered a similar is ...

Is there a recommended approach in Vuex to detect when a state change has occurred?

Our team has developed a Vuex module to store user-input data from a form. If the form has unsaved changes and the user tries to leave the page, we want to warn them so they can decide whether or not to proceed. It would be convenient if we could simply u ...

What is the process for removing items from an array in JavaScript that share the same values?

If you have an array of objects structured like the following: "medios":[ { "Key":"1", "Text":"Cheque" }, { "Key":"2", "Text":"Tarjeta de Crédito" }, { "Key":"3", ...

The login process in Next-auth is currently halted on the /api/auth/providers endpoint when attempting to log in with the

My Next-auth logIn() function appears to be stuck endlessly on /api/auth/providers, as shown in this image. It seems that the async authorize(credentials) part is not being executed at all, as none of the console.log statements are working. /pages/api/au ...

Discovering the method for retrieving post parameters in Node.js

I am currently utilizing Node.js with Express and the httpAsyncClient library in Android. I have sent a request to Express using Post, including parameters. The request goes through successfully, but I am unable to retrieve the parameter in Post. I have ...

What is the best way to transfer information from a single card within a collection of cards to a dialog window?

I'm facing a challenge in my CRUD application where I want to incorporate a confirmation step using a Material-UI dialog, but I'm struggling to pass the necessary data to the dialog. Currently, I have a list/grid of cards generated using .map(), ...

Encountering TypeError while attempting to assign an axios response to a data variable within a Vue component

Encountering the error message TypeError: Cannot set property 'randomWord' of undefined specifically at the line: this.randomWord = response.data.word; Confirming that console.log(response.data.word) does display a string. Vue Component Structu ...

How to save HTML content in a variable for future use in Next.js

When working with Next JS, my code resembles something like this: function Test() { return ( <section> <div>Test</div> </section> ); } Now, imagine that I want to have multiple entries here, gen ...

Warning: The use of the outdated folder mapping "./" in the "exports" field for module resolution in the package located at node_modulespostcsspackage.json is deprecated

I recently upgraded my Node to version 16 and since then I have been encountering this issue while building my Angular app. Warning: The folder mapping "./" used in the "exports" field of the package located at ".../node_modules/postcss/package.json" is de ...

What are the signs that an element was visible on screen prior to navigation?

Recently, I incorporated SlideUp and SlideDown jquery animations into my website. You can check it out by visiting (click the >>>). However, I noticed a small issue where when users navigate to a new page, they have to re-SlideUp the element that ...

When attempting to retry in Next.js, the props obtained from getServerSideProps may

Currently, I am facing an issue with sending axios requests in getServerSideProps and passing the value through props via SSR to the client. The challenge lies in including a token in the header using an instance. In case the token expires, I utilize refre ...

When using VueJS, clicking on one button will automatically disable all other remaining buttons

Currently, my setup involves three buttons displayed using a v-for loop, each with its own click method. I'm trying to implement a feature where clicking on one button disables the others, but also allows clicking on the active button to re-enable al ...

Creating unique identifiers and names for dynamically generated editable HTML table cells using JavaScript

Clicking the button will trigger the GenerateTable() function to dynamically create a table based on selected options from the drop-down menu as column headings. Below is the JavaScript code, along with instructions on how to assign IDs and names to each t ...

Creating a file logging system with console.log() in hapi.js

I have recently developed an Application with Hapi.js and have utilized good-file to record logs into a file. However, I am facing an issue where the logs are only written to the file when using request.log() and server.log() methods. My goal is to also lo ...

Organize an array of objects based on another array in JavaScript

I have been working on sorting an array of objects by comparing it with another object. The goal is to display the selected objects at the top and the rest below them. While I am currently achieving the desired output, I am interested in exploring ways to ...

Utilizing nested JavaScript objects results in receiving an empty object as the output

I have been encountering a challenge in my application while trying to register a user. The middleware implementation I have includes code that is supposed to create a user object when they input their first name, last name, email, and password. However, w ...

Change the behavior of a submit button to trigger a custom JavaScript function instead

I am faced with a challenge where I need to override the default functionality of a button in code that cannot be altered. Instead, I must ensure that when the button is clicked, a custom JavaScript method is called rather than submitting the form as it no ...

Error message encountered: "Attempted to serve a new HTML file but received the 'Cannot set headers after they are sent to the client' error."

I'm a beginner in NodeJS and I'm currently working on enhancing a sample project that utilizes the Spotify API and Express. In this project, users are required to authenticate on the homepage, after which they should be directed to a different HT ...

The data input into Express and Mongoose is failing to save

I am having trouble saving a new object, as one of the fields is not being saved even though all others are saved successfully. In my Mongoose schema, I have defined a property called superPlotId: const mongoose = require('mongoose'); const Geo ...

The Google Pie chart is displaying outside of the designated div area when placed inside a dropdown menu

Encountering an issue with my pie chart rendering outside of its parent div when placed within a dropdown menu. The chart successfully loads after the page is loaded, but only displays correctly if I hover over the dropdown and allow it to load. If I do ...