What is the best way to transform my arrays into objects or JSON through web scraping?

What is the most efficient method for transforming a scraped data array?

 [ 'item 1',    'item 2',   'item 3', 'item 4']  [ '$99',    '$99',   '$99', '$99']


                                              into object 

{ name: 'item 1', price: '$100', }{ name: 'item 2', price: '$100', }{ name: 'item 3', price: '$100', }


I attempted

var keys = [
        'name',
        'price'
    ]
const mainData = {} 
    for (i = 0; i < 10; i++) {
        let keyIdx = 0;
        for (j = 0; j < 2; j++) {
            if (l < 2) {
            //bundle.name and bundle.price contains above mentioned array of name and price
                mainData[keys[j]] = bundle.name[l];
                // keyIdx++;
                j++;
                mainData[keys[j]] = bundle.price[l];
            }
            


but it only outputs a single object { name: 'item 3', price: '$99' }


Answer №1

When working with two arrays of equal length, you have the option to iterate through one array and use the i to connect the name with the corresponding price.

 const items = ['item 1', 'item 2', 'item 3', 'item 4']
 const prices = ['$10', '$20', '$30', '$40']


 const output = items.map((item, i) => {
   return {
     item,
     price: prices[i]
   }
 });

 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

Utilizing jQuery to pinpoint the exact position within a Flexbox container

I have a unique setup with multiple boxes arranged using Flexbox as the container and list tags as individual boxes inside. These boxes are responsive and change position as the width is resized. My goal is to use jQuery to detect which boxes are touching ...

Creating a stunning image carousel in Vue by integrating a photo API: step-by-step guide

Trying to figure out how to create an image carousel in Vue using photos from an API. Currently able to display the photos using: <section class="images"> <img v-for="image in images" :key="image.id":src="image.assets.large.url"> &l ...

Drag and drop a Jquery image onto the div with its top left corner

Drop targets: <div id="targetContainer" style="width:100px; height:100px;> <div id="tar_0-0" class="target" style="position: relative; float:left; width:50px; height:50px; background-color: #fff;"></div> <div id="tar_1-0" class="t ...

Remove every other element from a JSON Array by splicing out the even-numbered items, rather than removing matching items

After receiving a JSON Array Output from a REST API, I am using ng-repeat to display the items on an HTML page. The structure of the received data is as follows: var searchresponse = [{ "items": [{ "employeeId": "ABC", "type": "D", "alive": "Y ...

Oops, it seems like the project is missing a `pages` directory. Please kindly create one in the project root. Thank you!

Initially, my project setup looked like this: public .next src pages components assets next.config.js It was functioning properly, but I made a structural change to the following: public src client next.config.js jsconfig.json pa ...

CSRF fails to execute during the initial post submission

This is my first time dealing with CSRF and reaching out to Stack Overflow for the first time. After struggling through the configuration, I finally managed to get it working almost perfectly. However, I ran into an issue where if I open a bookmarked page ...

What are the best practices for manually handling the json_encode function?

I have a set of data that needs to be displayed on a map. In order to achieve this, I need to format it into a JSON file according to Google Maps standards. Here's an example of the format: { "id": 1, "picture": "cité.jpg", "name": "Cité", "categor ...

Locate the div in the array that includes ValueA, and save ValueB from it into a new variable

When the button is clicked, I retrieve the current value of a Select control using the following code... $('#myBtn').on('click', function (clickEvent) { var nameSelected = document.getElementById('mySelectControl').getEle ...

Using PHP, create a variable that is determined by the contents of an

Picture this: $array(type=>$user_input); $level1 = "arbitrary 1"; $level2 = "arbitarty 2"; if( $type && $type != '' ){ switch ($type){ case 'level1': $levels = $level1; b ...

Looping through elements using .each in jQuery and accessing their values in the following iteration

Here is the code snippet I've been working on: var index=0; var load=0; $("td.load_ads").each(function(){ var loading=$(this); $.post('/self_coded_helpers/jpost_get_ads.php',{index:index,type:'fetch_id' ...

Programming in C: Creating Text Files with Random Numbers, Analyzing Occurrences, and Conducting Statistical Analysis

I am working on a program that generates random numbers and saves them to a new text file. The goal is to then analyze the generated values, counting how many times each number appears in the file (e.g. Number 1 has appeared "x" number of times). I expect ...

Angular Sending JSON Data via POST Request

Whenever I submit an empty form through my Angular application, the JSON being sent is as follows: {foo: {}} This causes a 500 error to occur on my server instead of the expected 422 error, since the server requires the following structure: {foo: {bar: ...

Are there any alternate keys present in the JSON object?

I am currently developing a program that utilizes a JSON file as input. Within this JSON file, there is code running in the background to retrieve a value. The structure of my JSON file is shown below: { "Machine Learning": { "URL1": "https:// ...

What is the best way to customize the link style for individual data links within a Highcharts network graph?

I am currently working on creating a Network Graph that visualizes relationships between devices and individuals in an Internet of Things environment. The data for the graph is extracted from a database, including information about the sender and receiver ...

What is the optimal method in modern C++ for creating and managing a 2D array effectively?

Looking for different solutions, I stumbled upon numerous options for this problem. While many suggest using std::array<4, std::array<4, int>> or std::vector<std::vector<int>>, I personally find them cumbersome and challenging to ...

Dealing with the complexities of Jquery Ajax and WCF Webservice integration:

I have developed a WCF Webservice method that accepts two parameters, both strings, and returns an XmlElement. Currently, I am encountering issues with an ASP.NET page that contains a JQuery AJAX call to this method. Despite trying to troubleshoot using o ...

Adding an object to an ArrayList: A step-by-step guide

I'm encountering issues with adding objects to the list. I have a list of floors, each floor containing rooms. I can successfully add a floor, but I'm unsure how to add rooms to the floor list. I've attempted to access floor[index] or id, b ...

Router DOM in conjunction with Next.js

I am attempting to extract the output of the code in navigation, but unfortunately it is generating a dreadful error: Unhandled Runtime Error Error: You cannot render a <Router> inside another <Router>. You should never have more than one in ...

Is the alert failing to appear during the onbeforeunload event across all web browsers?

Check out the following code snippet that is functional. window.onbeforeunload = function() { someAjaxCall(); } This code block, however, does not perform as expected: window.onbeforeunload = function() { someAjaxCall(); alert("Success !!"); ...

Exploring jQuery's capabilities with Cross-Domain URLs

I created a basic index.php file with the following code: <!DOCTYPE html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/httpGet.js"></script> <script type ...