JSON representation of 2 arrays

I am looking to combine 2 arrays in JSON format with keys and values.

MyArray1 [ "Orange:10", "Orange:5", "Banana:20", "Apple:5" ]
MyArray2 [ "Orange:5", "Banana:10", "Apple:15" ]

MyJSON   [
      {"fruit": "Orange", "value": 15},
      {"fruit": "Banana", "value": 20},
      {"fruit": "Apple ", "value": 5},
    ],[
      {"fruit": "Orange", "value": 5},
      {"fruit": "Banana", "value": 10},
      {"fruit": "Apple ", "value": 15},
    ]
  ]

I attempted this method but I require key-value pairs to concatenate my 2 arrays together:

MyArray1.forEach(function(val) {
                    var item = val.split(":");
                    var key = item[0];
                    var num = parseInt(item[1], 10);

                    if (MyArray1.hasOwnProperty(key)) {
                    MyArray1[key] += num;
                    } else {
                        MyArray1[key] = num;
                    }
                }); 

Answer №1

Here is a revised version summarizing the values of the same fruits. The values are now integers for easier addition. If you prefer strings, simply use arr[i].value=arr[i].value.toString(). Your feedback is appreciated.

var myArray1 =  [ "Orange:10", "Orange:5", "Banana:20", "Apple:5" ];
var myArray2 = [ "Orange:5", "Banana:10", "Apple:15" ];

var myObjectArray1 = arrayToObjectArray(myArray1);
var myObjectArray2 = arrayToObjectArray(myArray2);

var myOnlyOneObjectArray= myObjectArray1.concat(myObjectArray2);

var myResult = mergeObjectArray(myOnlyOneObjectArray,"fruit","value")

console.log(myResult);

function arrayToObjectArray(arr){
// Using map to transform each array row
var arr2 = arr.map(function(item) {
var items = item.split(":");
item = {};
item.fruit = items[0];
item.value = parseInt(items[1]);
return item;
});
return arr2;
}
 
function mergeObjectArray(arr,compareKey,addKey){
// Loop through arr in reverse and check for matching fruits to sum their values
for(var i = arr.length-1; i >=0;i--){
for(var j = 0; j < arr.length -1;j++){
if((arr[i][compareKey]==arr[j][compareKey]) && (i!=j)){ 
arr[j][addKey]+=arr[i][addKey];  
arr.splice(i, 1); 
break;
}
}
}
return arr;
}

Answer №2

Check out this example showcasing a simple transformation process: I created a basic function to convert a flat array into an array of objects, followed by grouping the two modified arrays into another array

var myFruits1 =  [ "Peach:8", "Pear:4", "Kiwi:12", "Grape:7" ];
var myFruits2 = [ "Peach:4", "Kiwi:9", "Grape:15" ];

var myFruits1Updated = updateArrayObjects(myFruits1);
var myFruits2Updated = updateArrayObjects(myFruits2);

var combinedResult = [myFruits1Updated, myFruits2Updated];

console.log(combinedResult);

function updateArrayObjects(arr){
var arrModified = arr.map(function(item) {
var itemsSplit = item.split(":");
item = {};
item.name = itemsSplit[0];
item.quantity = itemsSplit[1];

return item;
});
return arrModified;
}

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

Is it possible to showcase D3 charts on an .epub file?

For my research project, I am exploring the possibilities of .epub files and experimenting with embedding JavaScript code to display data visualizations. I am currently using calibre to convert an HTML file containing D3 scatterplots into an .epub. The s ...

What is the best way to initialize a value asynchronously for React context API in the latest version of NextJS, version

Currently, I'm working on implementing the React context API in my NextJS e-commerce application to manage a user's shopping cart. The challenge I'm facing is how to retrieve the cart contents from MongoDB to initiate the cart context. This ...

Deactivating Node.js files in vsCode for client-side JavaScript files

I'm facing a major challenge when it comes to coding with JavaScript. I have a JavaScript file that is using Node.js, which means I am unable to manipulate the DOM elements. Take this code snippet for example: var form = document.getElementsByClassNa ...

What is the best way to retrieve a value from a multiple select element being utilized by asmselect?

I have a form in my code that I am validating using a JavaScript function called sub(). Once the validation is successful, I am posting the data to a PHP file using $.POST. I am able to fetch the name field using its id, but I am facing issues with fetchin ...

Leveraging symbols in JSON with Python

I encountered an issue when working with JSON in Python recently, specifically related to special symbols. The problem can be seen in the following code snippet: import json app = { "text": "°" } print(json.dumps(app, ind ...

When navigating within a page, Firefox shows {{ }} tags while Chrome does not in AngularJS

After experimenting with various techniques, I managed to successfully hide the content section upon initial page load. However, when navigating within the page, the tags still appear. Any suggestions on how to resolve this issue? You can view the proble ...

Easily compare arrays using mathematical operators

In Perl, when comparing elements of arrays of the same length with a predictable order, we can utilize the each_arrayref function. This function can be integrated into useful subroutines or used directly: use List::AllUtils qw/each_arrayref/; my ($arr1, ...

Tips for saving HTML data locally

Is there a way to persist my HTML element tag data even after the user closes the browser? For example: <div class="classOne" data-random="50"> If I use jQuery to change the data attribute like this: $(".classOne").attr("data-random","40") How ca ...

The feature of filtering in Telerik software

I have a piece of JavaScript code that is supposed to run when the document is ready. However, when I apply telerik filtering, the function that should run on document ready is not working after the filter is applied. $(document).ready(function () { ...

`The enforcement of a function's parameter requiring it to be part of the generic type T`

Is there a way in my typescript function to ensure that all keys in the second argument belong to the object defined by the first argument? For example: mapTo([new KeyValue('a', 'b'), new KeyValue('x', 'y')], {key ...

Getting the backslash character to display correctly within a JSON object value in Java can sometimes be tricky, as it

How do I properly escape a backslash in a JSON value using Java? When trying to execute the below sample code, I encountered an org.json.JSONException: Illegal escape error at line 9. I am utilizing the json 1.0.0 jar - org.json String s1 = "{' ...

Delay in only a portion of the AJAX response

I created a chat application that is functioning correctly, but I am encountering an unexpected behavior. When a user sends a message, the user's name, time, and message should be displayed in order. However, currently, it seems like the username and ...

When exporting a Mongoose model, it mysteriously becomes undefined

I am encountering an issue when trying to import the DemandeTransports model from a specific file: //@/components/database/model/Schema.js import { Schema } from "mongoose"; import mongoose from "mongoose"; const userSchema = new Schem ...

Guide on creating a function that accepts an Array of strings as a parameter and displays the initial letter of each element individually on separate lines

I am currently tackling my initial JavaScript assignment which involves the task of creating a function that accepts an array of strings as its parameter and outputs the first letter of each element individually on separate lines. The unique requirement ...

Is it possible to simultaneously execute an animate and a fade out effect?

Is there a way to simultaneously move "app1" to the left and fade it out? Currently, the functions are executing one after the other. I want them to occur simultaneously, without the left movement happening before the fade out. Thank you! <!DOCTYPE h ...

"The text() or json() methods in Javascript's fetch function never seem to resolve, leaving the operation in a perpetual

In my new nextjs 13 project, I'm attempting to perform a fetch operation (unsure if it's related to JavaScript or nextjs) and using console.logs to monitor the code execution. let url = `${BASE}/${module}/${path}`; url += "?" + ne ...

Executing a query with a `has many` relationship in MongoDB: Step-by-step guide

In my setup with Node, Express, and backbone, I am successfully retrieving records from MongoDB collections using simple queries. However, I am struggling to understand how to query more complex data, such as the one below: db.employees.aggregate( [ ...

Using JavaScript/JQuery, change relative or viewport sizes to fixed sizes when the page loads

Wishing you a delightful day. As I work on my website, I find myself relying heavily on viewport units like vw and vh for all measurements such as font size, padding, margin, width, and height. These units provide the flexibility needed to ensure that the ...

Clicking on a single checkbox causes the entire input to become deactivated due to the way the system is

I'm encountering a puzzling issue that has me feeling like I know the solution, yet I don't. I set "State" to [checked]. The problem arises when, upon turning it into a map and clicking just one checkbox, the entire selection is clicked. To addre ...

Trouble with modifying style in Google Chrome and Internet Explorer prior to AJAX request

When utilizing AJAX, I have a common practice of setting up a loading indicator before each request to inform the user about the short wait. Usually, this is achieved by adding an animated loading gif. Interestingly, when performing this action in Firefox, ...