JavaScript: Converting an array of strings into an array of objects with proper formatting

After scanning barcodes, I have an array of strings that currently contains the following data:

var array = ['NEW', '1111', 'serial1', 'serial2, 'NEW', '2222', 'serial3', 'serial4']; 

To process this scanned data effectively, I need to convert the array into objects structured like this:

var objects = [
                {
                  order_id: '1111',
                  serial_numbers: ['serial1', 'serial2']
                },
                {
                  order_id: '2222',
                  serial_numbers: ['serial3', 'serial4']
                }
]

It is evident that the presence of 'NEW' in the array signifies the upcoming order_id (e.g. '1111'). Subsequently, there are multiple serial_numbers listed until the next occurrence of 'NEW'.

My attempt at structuring the array using indexes did not yield satisfactory results.

I appreciate any assistance you can provide!

Answer №1

To achieve the desired outcome, one can utilize the powerful reduce method

var array = [
  "NEW",
  "1111",
  "serial1",
  "serial2",
  "NEW",
  "2222",
  "serial3",
  "serial4",
];

const result = array.reduce((acc, curr) => {
  if (curr === "NEW") acc.push({ order_id: "", serial_numbers: [] });
  else {
    const last = acc[acc.length - 1];
    if (!last.order_id) last.order_id = curr;
    else last.serial_numbers.push(curr);
  }

  return acc;
}, []);

console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Hello there, I have a solution for parsing arrays with fixed serial numbers:

function parseArray(input) {
  let output = [];
  for (let i = 0; i < array.length; i++) {
    if (array[i] === 'NEW') {
      output.push({
        order_id: array[i + 1],
        serial: [array[i + 2], array[i + 3]]
      });
      i += 3;
    }
  }
  return output;
}

To see a live example, check out my stackblitz link: https://stackblitz.com/edit/web-platform-ec4kcw?file=script.js

UPDATE:

I have updated the function to handle arrays with varying lengths of serials:

function parseArray(input) {
  let output = [];
  let item = {};
  for (let i = 0; i < input.length; i++) {
    if (input[i] === 'NEW') {
      item = {
        order_id: input[i + 1],
        serial: []
      };
      output.push(item);
      i += 1;
    } else {
      item.serial.push(input[i]);
    }
  }
  return output;
}

Answer №3

Prior to creating objects, it is essential to process the unstructured array items into a more appropriate format. The following code serves this purpose:

var array = ['NEW', '1111', 'serial1', 'serial2', 'NEW', '2222', 'serial3', 'serial4'];

// Generate an array of arrays containing the serial numbers
// The initial element in each sub-array represents the order id
function parseOrders(items) {
  const orders = [];
  let orderItems = [];
  
  items.forEach((item) => {
    if (item === 'NEW') {
      if (orderItems.length > 0) {
        orders.push(orderItems);
      }
      orderItems = [];
    } else {
      orderItems.push(item)
    }
  })

  if (orderItems.length > 0) orders.push(orderItems);
  return orders;
}

function transformToObjects(orders) {
  const objects = [];
  orders.forEach((order) => {
    const orderId = order[0];
    const serialNumbers = order.slice(1);
    objects.push({
      order_id: orderId,
      serial_numbers: serialNumbers,
    })
  })
  return objects;
}

const orders = parseOrders(array);
const objects = transformToObjects(orders);
console.log(objects);

Answer №4

const result = array.reduce((prev, curr, index, arr) => {
if (curr === 'NEW') {
    return prev.concat({
        transaction_id: arr[index + 1],
        items: [arr[index + 2], arr[index + 3]]
    });
}
return prev;
}, []); 

Utilizing the reduce method simplifies obtaining the desired output format.

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

"Interactive table feature allowing for scrolling, with anchored headers and columns, as well as the option to fix

I'm in need of a table that has certain requirements, as shown in the image. https://i.stack.imgur.com/Z6DMx.png The specific criteria include: The header row (initially blurred) should remain fixed when scrolling down the table The first column s ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

Tips for changing the content of a td element to an input field and removing the displayed value

I am facing an issue with a dynamic table that displays names and input fields. When a name is displayed in a table row, the user has the option to delete that name. I am able to remove the value from a specific table row, but I am struggling to replace th ...

Transmit information from a Chrome extension to a Node.js server

Recently, I developed a basic Chrome extension that captures a few clicks on a specific webpage and stores the data in my content_script. Now, I am looking for ways to transmit this data (in JSON format) to my node.js file located at /start. I am seeking ...

Adjust the width of a textarea dynamically as you type by detecting keyup events

Two text areas have the same text formatting. Their IDs are textareaA and textareaB. I've successfully added functionality to resize textareaA on keyup. How can I make textareaB resize its WIDTH while the user is typing in textareaA? Here's wha ...

Govern Your Gateway with Expressive Logs

I'm facing some issues with the logs in my Express Gateway: Although I followed the documentation and enabled Express Gateway logs, I cannot locate any log files under my gateway root directory. Whenever I start the gateway using the command LOG_L ...

What is the best way to include message body in CDATA using strophe?

I have a task to create messages in a specific format by using the following code: $msg({to: 'user', from: 'me', type: 'chat'}).c("body").t('some data'); This code generates the message structure as follows: <m ...

Encountering overload error with Vue 3 and Axios integration

Currently utilizing Vue 3, Vite, Axios, and TypeScript. While my function functions properly in development, it throws an error in my IDE and during the build process. get count() { axios({ method: "get", url: "/info/count", h ...

The role of providers in Angular applications

After creating a component and service in my project, I followed the documentation's instruction to include the service in the providers metadata of the component for injection. However, I found that it still works fine even without mentioning it in t ...

Deciphering HTML encoding for text fields

As I transition from the Microsoft stack, specifically WPF, to HTML5, I apologize for any beginner-level questions. Today's topic is HTML encoding and decoding. Imagine an HTML5 application making AJAX calls to a C# backend using HTTP. The server al ...

Having trouble loading an image after successfully connecting to an API with react.js

I've been working on a custom fetch component to load images from the "the dog API" onto my page. However, I'm facing some issues with getting the images to display correctly. Can anyone spot what might be missing in my setup? App.js import &apo ...

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...

Having issue updating a MySQL table using an array of objects in JavaScript

Working on a personal project involving React.js for the front-end, Node.js/express for the back-end, and mySQL for the database. The current array is as follows: horaires = [ { jour: 'Lundi', horaire: 'Fermé' }, { jour: 'Mar ...

Transfer a csv file from a static webpage to an S3 bucket

Looking to create a webpage for uploading csv files to an S3 bucket? I recently followed a tutorial on the AWS website that might be helpful. Check it out here. I made some modifications to accept filename parameters in my method, and everything seems to ...

Failure of default option to appear in dropdown menu in Angular

I currently have a dropdown list in my HTML setup like this: <select id="universitySel" ng-model="universityValue" ng-options="university._id for university in universities"> <option value="-1">Choose university</option> ...

execute action after a specific point in time in the video is reached

How can I hide a div after a video has been playing for a certain amount of time? The code provided below seems like it should work in theory, but is currently not doing so. Any suggestions on how to fix this issue would be greatly appreciated! <body ...

Is there a more efficient method for replacing all attributes on cloned elements?

While this code does the job, I can't help but feel like it's a bit outdated. I'm not very experienced with JS/JQuery and only use them when necessary. My approach involves cloning an element and then replacing all of its attributes with on ...

Unable to refresh HTML table using Vuex data in Vue JS

I am new to working with Vue.js and particularly Nuxt. I am facing an issue with updating a table using data fetched from the backend. Even though I can see the data in the Vuex tab when the page loads, I cannot seem to populate the table with it. The func ...

The JQuery script functions properly when directly embedded in an HTML file, but fails to work when linked from an external file

While I'm working on some code using JQuery's .hover method, I've encountered an interesting issue. It seems to work fine when written directly in the main HTML file index.html, but for some reason, it fails to execute when written in a Java ...

How can I utilize match props in React JS with the Context API?

Currently working on a basic application that utilizes context API, fetch, and react hooks for all components except the context API component due to ongoing learning of hooks. The challenge lies in incorporating the match prop within the context API prov ...