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

Although there may be some issues with tslint, the functionality is operating smoothly

I am in the process of learning tslint and typescript. Currently, I am facing an issue that I need help with. Could you provide guidance on how to resolve it? Despite conducting some research, I have been unable to find a solution. The relevant code snippe ...

Member not found error with JQuery Autocomplete on browsers older than Internet Explorer 10

While constructing a web page with JQuery, I encountered issues with my autocomplete feature when testing it on IE8. The error message reads: SCRIPT3: Member not found. jquery-1.6.4.min.js, line 2 character 29472 After extensive research, I have been u ...

Transform an item into a map of the item's properties

I am faced with an object containing unknown key/value pairs in this format: myObj = { key_1: value_1, key_2: value_2, key_n: value_n } My goal is to transform it into a dictionary of structured objects like the one below: dictOfStructureObjec ...

The troubleshooting issue with jQuery animate Scrolltop malfunctioning

My goal is to use jQuery to scroll the page to a specific div when a button is clicked. Despite not seeing any errors in the JavaScript console, the page does not actually scroll to the desired location. I have tried placing the jQuery js file before and a ...

Does Mongoose use asynchronous saving?

Just starting out with mongoose and node. I'm trying to determine if the mongoose document.save method is asynchronous. Based on my observations, it seems to work even when not connected. Is there any way to know for sure when the document has been s ...

What steps do I need to take to integrate my RASA assistant into my personal website?

Deploying my rasa chatbot on my live website is my next step. While Rasa worked smoothly on my localhost server, as a newcomer to web development, I found the official guide provided by RASA in the link below a bit challenging to comprehend: The RASA guid ...

Escaping back slashes in Node.js

I am currently encountering an issue with escaping backslashes. Below is the code snippet that I have attempted. The problem lies in how to assign a variable containing an escaped slash to another variable. var s = 'domain\\username'; ...

Encountering issues with the phaser framework while setting up a server on xampp, faced with errors in javascript and html

Recently, I've been working on a game using Phaser and encountered some issues while trying to run the code in XAMPP. The game's base is located at htdocs/itw/test.html, with the necessary pngs and json file stored in htdocs/itw/assets/. The pngs ...

Eliminate Quotation Marks and Commas in String Data Using React

I created a code snippet to input data into a table and added a button function for downloading the entire table. However, when I open the downloaded file using notes or a text editor, it shows multiple double quotes and commas that I need to eliminate. He ...

Is there a way to effectively alter an object that has been assigned in a separate file?

Seeking Assistance: I am facing an issue in my current project where I need to store a javascript object in an external file and then export it using module.exports. The challenge now is that I want another file to be able to modify a specific value withi ...

Error: The react.js application is unable to access the property 'classList' of a null object

I've encountered a bug that's been causing me some trouble. Every time I try to run my react application, I keep getting an error message that reads TypeError: Cannot read property 'classList' of null. As someone who is new to react, I& ...

script to pause video using jQuery

I have a script that works perfectly, but currently it only stops an instance of a playing video if a new video is started. I want to modify the script so that ALL instances of playing videos are stopped when the function stopAllButMe(); is called. Can s ...

What causes useEffect to run twice in React and what is the best way to manage it effectively?

I'm currently facing an issue with my React 18 project where the useEffect hook is being called twice on mount. I have a counter set up along with a console.log() inside the useEffect to track changes in state. Here's a link to my project on Code ...

Discover the power of utilizing JavaScript to sort through table rows by filtering them based on the selections of multiple checkbox

How can I create interdependent logic for checkbox sections in a form to filter based on all selections? I am looking for help with my code snippet that showcases checkboxes controlling the visibility of table rows: $(document).ready(function() { $(" ...

Cached images do not trigger the OnLoad event

Is there a way to monitor the load event of my images? Here's my current approach. export const Picture: FC<PictureProps> = ({ src, imgCls, picCls, lazy, alt: initialAlt, onLoad, onClick, style }) => { const alt = useMemo(() => initial ...

Is there a way to determine if a value exists within an array of objects?

Is it possible to determine if a specific value is present in an array of objects? I've tried a method, but it always returns false. What would be the most effective way to solve this issue? My approach: var dog_database = [ {"dog_name": "Joey" ...

Navigating through the various iterations of jQuery

Unique Case Study I'm currently facing a dilemma involving the integration of jstree and jquery-ui datepicker. The scenario is this: I am attempting to utilize jquery-ui-datepicker on an input element that is dynamically inserted into the DOM after ...

Invoke the callback function before executing the next function

There is a function that calls an API: const response = fetch(APIfunctonName, { method: "POST", body: JSON.stringify(searchRequest), headers: { "Content-type": "application/json; charset=UTF-8", }, }) ...

KnockoutJS is unable to assign a negative value to an input field

Is there a way to assign the value of an <input> as false? It seems to work fine with true. Data Model: function DataModel(){ self = this; self.Flag = ko.observable(false); }; HTML Code: <input type="text" data-bind="value:Flag"/> ...

Sending JSON Data over URL

I am facing a challenge with passing data between two HTML files. My initial solution involved sending the data through the URL using the hash and then parsing the link using JSON.parse(window.location.hash.slice(1));. This method worked for a few attempts ...