Tips for breaking apart elements of a JavaScript array when a specific delimiter is present in an object property

I am facing a challenge with an array of objects where some properties contain commas. My goal is to split these properties into new objects and recursively copy the rest of the properties into new array elements.

For example, consider this original array:

[ { 
    prop1: ' text1 , text2 , text3 ',
    prop2: 'stuff1',
    prop3: 'stuff1',
    prop4: 'stuff1',
    prop5: 'https://www.stuff1.com' },

  { 
    prop1: ' text1 , text2 , text3 ',
    prop2: 'stuff2',
    prop3: 'stuff2',
    prop4: 'stuff2',
    prop5: 'https://www.awefewfew.com' },

 ]

We need to transform it into the following structure:

[ { 
    prop1: 'text1',
    prop2: 'stuff1',
    prop3: 'stuff1',
    prop4: 'stuff1',
    prop5: 'https://www.stuff1.com' },

    { 
    prop1: 'text2',
    prop2: 'stuff1',
    prop3: 'stuff1',
    prop4: 'stuff1',
    prop5: 'https://www.stuff1.com' },

    { 
    prop1: 'text3 ',
    prop2: 'stuff1',
    prop3: 'stuff1',
    prop4: 'stuff1',
    prop5: 'https://www.stuff1.com' },   

  { 
    prop1: 'text1',
    prop2: 'stuff2',
    prop3: 'stuff2',
    prop4: 'stuff2',
    prop5: 'https://www.awefewfew.com' },

      { 
    prop1: 'text2',
    prop2: 'stuff2',
    prop3: 'stuff2',
    prop4: 'stuff2',
    prop5: 'https://www.awefewfew.com' },

      { 
    prop1: 'text3',
    prop2: 'stuff2',
    prop3: 'stuff2',
    prop4: 'stuff2',
    prop5: 'https://www.awefewfew.com' },  
 ]

The idea is to split at prop1 and then recursively copy all other properties into the new array element.

Additionally, I managed to solve a similar problem in Google Sheets but had difficulty translating it to vanilla JavaScript:

function splitColumnAndRepeatRows(anArray, splitColumnIndex) {
  var output = [];
  for (i in anArray){ 
    var splitArray = anArray[i][splitColumnIndex].split(","); 
    for (j in splitArray){ 
      var row = anArray[i].slice(0); 
      row[splitColumnIndex] = alltrim(splitArray[j]); 
      output.push(row); 
    }
  }
  return output;
}

function alltrim(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

Answer №1

I appreciate the efficiency of using array.concat in combination with reduce() and map() for this task. There are certainly multiple approaches to achieving the desired outcome. It's worth noting that the strings in your prop1 may not always be formatted with spaces, so a simple regex is used here to remove any unnecessary whitespace.

let arr = [ { prop1: ' text1 , text2 , text3 ',prop2: 'stuff1',prop3: 'stuff1',prop4: 'stuff1',prop5: 'https://www.stuff1.com' },{ prop1: ' text1 , text2 , text3 ',prop2: 'stuff2',prop3: 'stuff2',prop4: 'stuff2',prop5: 'https://www.awefewfew.com' },]

let final = arr.reduce((a, {prop1, ...obj}) => a.concat(
        prop1.trim()
        .split(/\s*,\s*/)
        .map(prop => ({prop1: prop, ...obj}))
    ), [])

console.log(final)

Answer №2

Implement a solution using the .reduce method to loop through the provided data. This code snippet breaks down the values in prop1 by splitting them at each comma and then adding them to an array:

const input=[{prop1:' text1 , text2 , text3 ',prop2:'stuff1',prop3:'stuff1',prop4:'stuff1',prop5:'https://www.stuff1.com'},{prop1:' text1 , text2 , text3 ',prop2:'stuff2',prop3:'stuff2',prop4:'stuff2',prop5:'https://www.awefewfew.com'},]
const ouput = input.reduce((accum, { prop1, ...rest }) => {
  const prop1s = prop1.trim().split(' , ');
  prop1s.forEach(prop1 => accum.push({
    prop1,
    ...rest
  }));
  return accum;
}, []);
console.log(ouput);

Answer №3

Utilize the reduce, split, and forEach methods

let information = [
  {
    prop1: ' item1 , item2 , item3 ',
    prop2: 'details1',
    prop3: 'details1',
    prop4: 'details1',
    prop5: 'https://www.details1.com'
  },

  {
    prop1: ' item1 , item2 , item3 ',
    prop2: 'details2',
    prop3: 'details2',
    prop4: 'details2',
    prop5: 'https://www.awefewfew.com'
  }
]
let result = information.reduce((r, object) => {
  object.prop1.split(',').forEach(value => {
    r.push(Object.assign({}, object, { prop1: value.trim() }))
  })
  return r
}, [])
console.log(result)

Answer №4

Give this a shot:

let data = [{ 
    property1: ' value1 , value2 , value3 ',
    property2: 'stuff1',
    property3: 'stuff1',
    property4: 'stuff1',
    property5: 'https://www.stuff1.com' },
  { 
    property1: ' value1 , value2 , value3 ',
    property2: 'stuff2',
    property3: 'stuff2',
    property4: 'stuff2',
    property5: 'https://www.awefewfew.com' }];
    
 let newArray = [];   
 
 for (let index in data) {
   let splitValues = data[index].property1.split(',');
   
   splitValues.map(item => {
     newArray.push({
       "property1": item,
       "property2": data[index].property2,
       "property3": data[index].property3,
       "property4": data[index].property4,
       "property5": data[index].property5
     });
   });
 }
 
 console.log(newArray);

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

The second pop-up modal fails to appear

I have successfully implemented 2 modal windows with the help of bootstrap. The first modal is used for adding a user to the database, and the second one is meant for editing an existing user. While the first modal works perfectly fine, the editing modal d ...

You do not have permission to access the restricted URI, error code: 1012

What is the best solution for resolving the Ajax cross site scripting issue in FireFox 3? ...

Discover how ReactJS can dynamically display or hide div elements based on specific conditions being met within JSON data

How do I show or hide a div based on a condition in React, using data from a JSON array? I have implemented the code below, but changing the value of isPassed={resultPass.pass} to isPassed={resultPass.failed} still displays the result as pass. I came acro ...

Retrieving JSON information from asynchronous JavaScript and XML (AJAX)

I am struggling with making a URL that contains JSON Data work properly. The issue lies in the data field - I am unsure of what to input here as it is currently undefined. My goal is to store an array of the JSON data received from the ajax request. What ...

Obtain the option tag's name

One of my challenges is working with a dynamically created dropdown in HTML and having a dictionary in the back-end to retrieve keys. As users keep adding options to the dropdown, I face the issue of not having a value attribute like this: <option valu ...

Refresh the Google Maps location using GPS coordinates

Currently, I am working with an Arduino that has a GPS chip and processing NMEA strings with Python. I have an HTML file set to auto-refresh every x seconds to update the marker's position. However, I would like to update the position information with ...

An error has occurred in the callback function for the watcher "function () { return this._data.$$state }": "Error: [vuex] It is forbidden to modify the vuex store state outside of a mutation"

Here is a screenshot of the error I encountered in the console This is the method that I am using The issue seems to be happening in mounted I have also included MapState in the Computed section While my code is currently functional, I am puzzled by th ...

Sending a Boolean value from a child component to its parent state in React JS

Within my application, I have implemented a login feature in the navbar component. However, I am encountering an issue with updating a variable in the main component upon successful login. Although I have successfully managed to set up the login functional ...

Use the document.getElementById function in JavaScript to dynamically retrieve elements based on user input in an HTML document. This will

I am currently working towards creating a gallery using pure JavaScript. To start, I am experimenting with a model that involves two buttons - when button #1 is clicked, the string "1.jpg" appears below, and when button #2 is clicked, "2.jpg" is displayed. ...

How can I effectively monitor and track modifications to a document's properties in MongoDB?

I'm wondering how to effectively track the values of a document in MongoDB. This involves a MongoDB Database with a Node and Express backend. For example, let's say there is a document within the Patients collection: { "_id": "4k2lK49938d ...

There seems to be an issue with the messages array in the Chatfuel Json API plugin. While only a text object is

Just getting started on the chatfuel bot platform. Currently using the json api plugin (Refer to the documentation here: ) Here is the JSON response I'm generating in my backend for the plugin, with this as my backend URL: { "messages": [ { ...

Is coffeescript supported by Moovweb?

Lately, I've been researching the Moovweb platform and I'm curious about its compatibility with CoffeeScript. Could someone share a code example to demonstrate how Moovweb works with CoffeeScript? ...

Question: How can I use the jQuery datepicker to ensure that the selected date remains in the

I recently created a webpage using a combination of HTML, PHP, and jQuery. The PHP script is designed to load all data where the date matches the one selected in the text input field generated by the jQuery datepicker. However, I encountered a problem whe ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...

I'm struggling to understand how to interpret this. The v-tab function seems to be generating a button with various properties, but I'm unsure which specific property is related to

The V-tab below generates the button known as the right one on the v-app-bar: https://i.stack.imgur.com/DzNmq.png <v-tab :to="'/demo'" active-class="text--primary" class=&quo ...

PUPPETER - Unpredictable pause in loop not functioning as expected

Having an issue with this specific part of the code: (async () => { const browser = await puppeteer.launch({ headless: false, // slowMo: 250 // slow down by 250ms }); const page = await browser.newPage(); //some code // CODE ABOVE WORKS, ...

A solo-dimensional array generated within a PHP while loop

Is there a way to extract the value of an array that is enclosed within a while loop and then use it outside of the loop? I managed to achieve this using the following code: $xyz = array(); while($row2 = mysql_fetch_assoc($result2)) { $value = $row2[& ...

Event fails to trigger when attached to different elements

Currently, I have an onchange event linked to the input text box and an onclick event attached to a text link. Interestingly, when I click on the link after editing the textbox, the click event does not trigger - instead, the change event is fired. If you ...

How do I make a component in React delete itself from a page when its internal state changes?

For instance: {!loading ? (data.map((v, i) => { return <Card key={i} title={v.name} image={v.pictures.sizes[4].link}} /> }) These cards are displayed as a series of components on the main screen. Each card ...

Different Categories of Array Deconstruction

While iterating through an array, I am utilizing destructuring. const newArr = arr.map(({name, age}) => `${name} ${age}`) An error occurs in the above code stating: Binding element 'name' implicitly has an 'any' type To resolve th ...