Transform an array of string values that occur multiple times into an array of objects organized by their index

Assuming I have a list structured as follows:

[
    "id1", "01-01-2019", "name1", "€ 5,60",
    "id2", "02-01-2019", "name2", "€ 5,70",
    "id3", "03-01-2019", "name3", "€ 5,20",
    ...
]

and my goal is to transform it into a list of JSON objects like this:

[
    {
        "id": "id1", 
        "date": "01-01-2019", 
        "name": "name1", 
        "value": "€ 5,60"
    },
    {
        "id": "id2", 
        "date": "02-01-2019", 
        "name": "name2", 
        "value": "€ 5,70"
    },
    {
        "id": "id3", 
        "date": "03-01-2019", 
        "name": "name3", 
        "value": "€ 5,20"
    },
    ...
]

What is the most efficient method to accomplish this task using JavaScript?

Answer №1

If I were to implement this, I would opt for a straightforward while loop approach with an initial assertion:

console.assert(data.length % 4 === 0); // This line ensures the data array is divisible by 4
const result = [];
let i = 0;
while (i < data.length) {
    result.push({
        id: data[i++],
        date: data[i++],
        name: data[i++],
        value: data[i++]
    });
}

Here's a practical demonstration:

const data = [
    "id1", "01-01-2019", "name1", "€ 5,60",
    "id2", "02-01-2019", "name2", "€ 5,70",
    "id3", "03-01-2019", "name3", "€ 5,20"
];

console.assert(data.length % 4 === 0);
const result = [];
let i = 0;
while (i < data.length) {
    result.push({
        id: data[i++],
        date: data[i++],
        name: data[i++],
        value: data[i++]
    });
}

console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
}

Answer №2

This particular method appears to offer the most efficiency as the loop only runs a quarter of the total length. If you have any alternative suggestions, please don't hesitate to share.

const data = [
    "id1", "01-01-2019", "name1", "€ 5,60",
    "id2", "02-01-2019", "name2", "€ 5,70",
    "id3", "03-01-2019", "name3", "€ 5,20",
    'id4', '03-01-2019'
];

const resultArray = [];
for (let i=0; i < data.length; i += 4) {
  const object = {};
  object.id = data[i];
  object.date = data[i + 1] ? data[i + 1] : 'NA'; // This will verify if the index is present or not.
  object.name = data[i + 2] ? data[i + 2] : 'NA';
  object.amount =data[i + 3] ? data[i + 3] : 'NA';
  
  resultArray.push(object);
}

console.log('resultArray = ', resultArray);

Answer №3

If you want to achieve this without using any loops, one way is to utilize the Array.reduce() method. With this approach, you can populate your output array by adding a new item every 4 iterations of your input data:

const data = [
    "id1", "01-01-2020", "name1", "$ 10.00",
    "id2", "02-01-2020", "name2", "$ 15.00",
    "id3", "03-01-2020", "name3", "$ 20.00",
];

const result = data.reduce((acc, _, i, arr) => {
  if (i % 4 === 0) {
    acc.push({ id: arr[i], date: arr[i+1], name: arr[i+2], value: arr[i+3] });
  }
  return acc;
}, []);

console.log(result);

Answer №4

To break down the array into smaller subarrays and then convert those subarrays into objects:

const arr = [
    "id1", "01-01-2019", "name1", "€ 5,60",
    "id2", "02-01-2019", "name2", "€ 5,70",
    "id3", "03-01-2019", "name3", "€ 5,20"
]

const result = chunk(arr, 4).map(item => ({ id: item[0], date: item[1], name: item[2], cost: item[3]}))

console.log(result)

function chunk(arr, size) {
const result = []

for (let i = 0; i < arr.length; i += size)
result.push(arr.slice(i, i + size))

return result
}

Answer №5

You have the option to destructure sections of an array and create a new object for appending.

const generateObject = ([id, date, name, value]) => ({ id, date, name, value });

var data = ["id1", "01-01-2019", "name1", "€ 5,60", "id2", "02-01-2019", "name2", "€ 5,70", "id3", "03-01-2019", "name3", "€ 5,20"],
    i = 0,
    result = [];

while (i < data.length) {
    result.push(generateObject(data.slice(i, i += 4)));
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №6

Utilize the Array.from method to accomplish a task without hardcoding keys in a loop. This approach is suitable for processing any number of predetermined keys as long as the input array data is valid.

const array = [
    "id1", "01-01-2019", "name1", "€ 5,60",
    "id2", "02-01-2019", "name2", "€ 5,70",
    "id3", "03-01-2019", "name3", "€ 5,20",
]

const keys = ["id", "date", "name", "value"],
    length =  array.length / keys.length;

const output = Array.from({ length }, (_, i) =>
    keys.reduce((result, key, j) => ({ ...result, [key]: array[i * keys.length + j] }), {})
);

console.log(output)

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

Why can't we import Angular 4 as a library similar to AngularJS?

Why was AngularJS introduced as a script to import in an HTML page? However, in the newer version Angular 4, we need to use a web server to launch the application? Is it because AngularJS is not considered a framework but Angular 4 is? Thank you. ...

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...

How to initiate focus on Angular 2 MdInputContainer after the view has been

I am encountering an issue with setting focus on the first md-input-container element within a component when the view loads. Despite implementing a @ViewChild property and calling focus on it in the ngAfterViewInit method, the focus does not seem to be wo ...

Building a div element within a React function

For an exercise, I need to create an input field and a button. The goal is to display the text from the input field in a div/span below when the button is clicked. If I change the text in the input field and click the button again, the displayed text shoul ...

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

What is causing my reusable component to malfunction when used in conjunction with the "setInterval" function?

I have created a custom <Loader /> component in which I can pass the text it is rendering and the speed as props. The code for the component is shown below: class Loader extends Component { constructor(props) { super(props); this.state = { ...

maximum number of results in google custom search limit

I'm trying to retrieve the top 40 results from the Google API, but when I limit the result using the code below, it doesn't seem to work. How can I achieve getting the top 40 results with the Google API? <script> (function() { ...

How to convert Firebase snapshot JSON data to text format instead of an object in Vue.js

After successfully pulling the data, it shows up as an object in my view: { "-MH8EpUbn1Eu3LdT0Tj0": { "code": "https://www.apesyntax.com", "content": "This is the tut content", "date": "2020- ...

Styling Form validation with Ant Design

Can a className prop be included in the Form.Item validation? <Form.Item name="username" rules={[ { required: true, message: '...' }, className="customValidation" //<- attempting to add a className but it is not fu ...

Is there a way to prevent the conversion of .json/.webmanifest URLs into base64 strings?

I've been grappling with an issue for quite some time now. In my VSCode vite-react-typescript project, I have a link in the index.html file pointing to a webmanifest, which is essentially a json file with a different extension. After building my app, ...

Mongoose discovers an unexpected empty array

My task is to locate a SoldProduct with an intimeOrderNumber value of '3'. var query = { intimeOrderNumber: '3' }; However, my search result returns an empty array. SoldProduct.find(query, function(err, soldProducts) { if (err) { ...

What is the best way to incorporate JavaScript in a repeater?

I am currently working on an asp.net project that involves using a repeater. <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1"> <HeaderTemplate> <asp:label ID="lblexp" runat="server" Text="05/11/1 ...

Putting together Modular Client-side JavaScript

Is there a way in Node.js to dynamically "require()" javascript files similar to PHP's require function? It would be great to use this feature in my client-side code for development purposes without actually calling a specific javascript function. Rat ...

Aligning container divs at the center in various screen resolutions

I recently constructed a portfolio website using Bootstrap and Isotope JS. In my layout, I have a container div which works perfectly when viewed on a desktop browser - displaying 3 divs in one line. However, the issue arises when the resolution changes an ...

Leveraging variables in a GET call

For a while now, I've been struggling with a seemingly simple issue. When I try to make a GET request using parameters in the query, it just doesn't work for me. However, if I use a full query without parameters, it works fine. Here is the code ...

What is the best method to eliminate elements from a queue using JavaScript?

I recently attempted to incorporate a queue feature into my JavaScript code. I found some helpful information on this website. While I successfully managed to add items to the queue, I faced difficulties when attempting to remove items from it. var queue ...

Ruby on Rails JSON API - flawless JSON without any errors

When I am displaying an array of ActiveRecord items, each has been processed through the valid? method so errors are already defined. The rendering of the array is done as follows: render json: array_of_objects I have ActiveModelSerializers.confi ...

Error: null does not have the property 'renderView' to be read

My goal is to set up a main page in React.js with two buttons: Option 1 and Option 2. Clicking on Option 1 should redirect the user to the Main1 page, while clicking on Option 2 should lead them to Main2. It seems straightforward, but I am encountering the ...

Connectivity issue: Socket.io fails to register user upon connection

Upon connecting to the page, I expect to see the message 'a user connected' printed on the command line using node.js. However, this message is not being displayed, indicating that the user's visit to the page is not being registered (all ac ...

Serialization with Gson based on field values

I have a custom Java object called MyGsonPojo with fields valueOne, valueTwo, and valueThree. I need to serialize this object into a JSON body for a server call, but some fields are optional and the API reacts differently based on default or null values (u ...