Using a conditional statement in a JavaScript loop

Here is the data I have:

    companyList: [
      {
        company_name: 'company1',
        item: 'item1'
      },
      {
        company_name: 'company1',
        item: 'item2'
      },
      {
        company_name: 'company1',
        item: 'item3'
      },
      {
        company_name: 'company2',
        item: 'item4'
      }
    ]

This is the desired output format:

    result: [
      {
        company_name: 'company1',
        product: [
          { item: 'item1'},
          { item: 'item2'},
          { item: 'item3'}
        ]
      },
      {
        company_name: 'company2',
        product: [
          { item: 'item4'}
        ]
      }
    ]

How can I achieve this output using map?

Answer №1

To achieve the desired output efficiently, you can iterate through the array of companyList with a time complexity of O(n). Here's a sample code snippet to demonstrate this:

var companyList = [{
  company_name: 'company1',
  item: 'item1'
}, {
  company_name: 'company1',
  item: 'item2'
}, {
  company_name: 'company1',
  item: 'item3'
}, {
  company_name: 'company2',
  item: 'item4'
}];

var tempObj = {};
companyList.forEach((companyObj) => {
  if(tempObj[companyObj.company_name]){
    tempObj[companyObj.company_name].product.push({item: companyObj.item});
  } else {
    tempObj[companyObj.company_name] = {
      company_name: companyObj.company_name,
      product: [{item: companyObj.item}]
    }
  }
});
var result = Object.values(tempObj);
console.log(result);

Answer №2

You have the ability to utilize the reduce method in order to generate a new array

let companyList = [{
    company_name: 'company1',
    item: 'item1'
  },
  {
    company_name: 'company1',
    item: 'item2'
  },
  {
    company_name: 'company1',
    item: 'item3'
  },
  {
    company_name: 'company2',
    item: 'item4'
  }
]

let result = companyList.reduce(function(acc, curr) {
  // Implement findIndex to locate the index of the object with matching company_name
  let findIndex = acc.findIndex(function(item) {
    return item.company_name === curr.company_name;
  });
  // If company_name does not exist, -1 will be returned
  if (findIndex === -1) {
    let obj = {};
    // Create a new object and push the value into it
    obj.company_name = curr.company_name;
    obj.product = [{
      item: curr.item
    }];
    acc.push(obj)
  } else {
    // If the company_name exists, update the product list
    acc[findIndex].product.push({
      item: curr.item
    })
  }
  return acc;
}, []);
console.log(result)

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

Tips for using regular expressions with the find method in JavaScript?

Welcome to my Object: let data = [{ "title": "User info", "category": "personal", "userId": "abc12345" }, { "title": "Customer Info", "category": ...

"Troubleshooting: NuxtJs vue-flip feature stuck on front side, not rotating to

I have recently installed the vue-flip plugin in a NuxtJs (VueJS) project that I created using the command: npx create-nuxt-app <project-name>. In the index.vue file, I simply added: <vue-flip active-click="true"> <div slot="front"> ...

Exploring the Power of JSONObject and JSONArray in Jmeter

Having an issue with constructing a Json for Amazon Kinesis. The Json needs to follow this format: { "Records": [ { "Data": "XzxkYXRhPl8x", "PartitionKey": "partitionKey1" }, { "Data": "f1PxF ...

Stop $watchCollection from initializing on start

I have an array called "$scope.postits" that I want to persist every time it changes. To achieve this, I added a $scope.$watchCollection on this element to monitor changes and save the data. The issue is that the $watch function gets triggered 3 times when ...

Is it possible to incorporate an element using absolute positioning using jQuery or Javascript?

When trying to add a new element on the screen, I am facing an issue with the absolute positioning not working properly. Sample Code in Javascript function drawElement(e,name){ $("#canvas").append("<div id='" + name + "' class='e ...

Exploring the potential of Raygun.io with Angular Universal

We are currently integrating Raygun.io APM into our Angular 8 app that utilizes Angular Universal. Raygun.io offers a client side javascript library, but to use it with Angular Universal, we need to create a DOM window API. This can be achieved by install ...

What is the process of transforming a string into a JSON object?

var str = '""{""as"":""N9K-93180YC-EX""}""'; I attempted to remove the extra quotes using a regular expression: var str1 = str.replace(/\"/g, ""); After removing the extra quotes, the string now looks like "{as:N9K-93180YC-EX}". However, ...

Changing the parent scope from the child component does not automatically reflect changes in an ng-repeat

I am facing an issue with the communication between a child controller and a parent controller. I have a function that adds data to a parent array which is used in an ng-repeat directive. Although the parent array gets updated correctly and its length is ...

The Bootstrap switch feature may encounter issues when trying to operate on dynamically generated checkbox inputs

My website is equipped with a mix of essential scripts: jQuery, Bootstrap, Modernizer, and JSON2HTML. I am trying to implement the following code snippet: <script> $('#my01Switch').bootstrapSwitch({ onText: 'ON', ...

Mapping the Way: Innovative Controls for Navigation

Currently, I am utilizing the HERE maps API for JavaScript. However, I would like to customize the design of the map controls similar to this: Below is an example for reference: HERE EXAMPLE Is it feasible to achieve this customization? ...

The semantic UI search functionality is malfunctioning

My experience with semantic ui involves encountering an issue where the search result on a website appears empty, despite finding the JSON result in my console. This is the JavaScript code I am using: $('.ui.search').search({ apiSettings: { ...

What is the quickest way to implement an instant search feature for WordPress posts?

Today, I have a new challenge to tackle on my website. I am determined to implement an INSTANT SEARCH feature that will search through all of my posts. One great example to draw inspiration from is found here: Another impressive implementation can be se ...

Using scripted <svg> with <defs> and attempting to reference it via JavaScript results in failure

My goal is to dynamically generate svg path elements in html using JavaScript. I would like to place these paths within a <defs> element so that they can be reused later in <use> xlink:href elements. However, after creating the paths (by pr ...

Javascript - When I preview my file, it automatically deletes the input file

My form initially looked like this : <form action="assets/php/test.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> ...

Combining Objects within an Array in JavaScript When Certain Conditions Are Satisfied

In my scenario, I am seeking assistance with merging the values of objects in an array if the id matches the warehouse_item_id. Specifically, there are two objects that need to be merged: id 191 and id 52 because id 52 has a warehouse_item_id of 191. Ple ...

Issues with Datepicker functionality in Bootstrap 5 are causing it to malfunction or not display

I am having trouble incorporating a timepicker on my webpage with bootstrap 5. The calendar feature isn't loading properly, preventing me from selecting any dates. I'm unsure if the issue lies with an error on my end or if the plugin isn't c ...

javascriptEmbed youtube video thumbnail dynamically as users input a URL

I am currently working on a React frontend for my web app. One of the features I want to implement is a URL input box, with an image display panel below it. The goal is that when a user enters a YouTube URL into the input box, the thumbnail of the correspo ...

Validation in AngularJS is limited to only accepting integers with the use of the

Can you help me with validating positive integer numbers using the ng-pattern attribute? Currently, I have this pattern: ^[0-9]{1,7}(\.[0-9]+)?$/, but it also allows decimal values. I want to restrict it to only accept whole numbers. ...

Differences between JavaScript's window.onload and body.onload functionsWhen

My inquiry is similar yet slightly distinct from the one queried here: window.onload vs <body onload=""/> The comparison in that prior query was between utilizing window.onload and inline js. My question pertains to the disparity between ...

Angular proxy - Syntax error found in proxy configuration file: proxy.conf.json

My Angular 6 setup is configured to make HttpRequests, but I encountered a problem that requires me to run them through a proxy. To address this issue, I created a proxy.conf.json file next to my package.json: { "/loans/": { "target" : "https://api. ...