Trim JSON using JavaScript

I'm currently working on reducing a JSON array. Within the array, there are other objects, and my goal is to convert their attributes into their own separate array.

Reduce Function:

// parsed.freight.items is the path
var resultsReduce = parsed.freight.items.reduce(function(prevVal, currVal){
    return prevVal += currVal.item
},[])
console.log(resultsReduce); 
// two items from the array
// 7205 00000
console.log(Array.isArray(resultsReduce));
// false

The reduce function is somewhat functional as it retrieves both the item values from the items array. However, I am facing a couple of challenges.

1) The reduce method does not return an array as expected based on the isArray test.

2) My aim is to create a function that allows me to iterate through all the attributes in the array such as qty, units, weight, paint_eligible. I'm struggling with passing a variable to the currVal.

Attempted Solution:

var itemAttribute = 'item';
var resultsReduce = parsed.freight.items.reduce(function(prevVal, currVal){
    // Pass parameter here for iteration purposes
    // I intend to create a function and loop through the array of attributes
    return prevVal += currVal[itemAttribute]
},[])

JSON Data:

var request = {
"operation":"rate_request",
"assembled":true,
"terms":true,
"subtotal":15000.00,
"shipping_total":300.00,
"taxtotal":20.00,
"allocated_credit":20,
"accessorials":
{
    "lift_gate_required":true,
    "residential_delivery":true,
    "custbodylimited_access":false
},
"freight":
{
    "items":
    // Array to be reduced
    [{
        "item":"7205",
        "qty":10,
        "units":10,
        "weight":"19.0000",
        "paint_eligible":false
    },
    {   
        "item":"1111",
        "qty":10,
        "units":10,
        "weight":"19.0000",
        "paint_eligible":false
    }],

    "total_items_count":10,
    "total_weight":190.0},

    "from_data":
    {
        "city":"Raleigh",
        "country":"US",
        "zip":"27604"
    },
    
    "to_data":
    {
        "city":"Chicago",
        "country":"US",
        "zip":"60605"
    }
}

Thank you in advance!

Answer №1

If you're looking to extract an array of items, consider using Array#map

var resultsReduce = parsed.freight.items.reduce(function (array, object) {
    return array.concat(object.item);
}, []);

To retrieve values with a specified key, you can use bracket notation as shown in the example below:

object.property
object["property"]
var key = 'item',
    resultsReduce = parsed.freight.items.reduce(function (array, object) {
       return array.concat(object[key]);
    }, []);

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

Unique issue: Angular encountering a syntax error exclusively in Internet Explorer browser

Encountered an issue with a JavaScript code snippet within my angular project. It throws a syntax error in IE 11, but runs smoothly in Chrome. Interestingly, this particular function is not even called on the initial page load, yet the error persists. Upo ...

Conceal a div if the second div contains no content

Although this question may have been posed in other discussions, I am struggling to make this code work on my WordPress website. if ($(".objectA").html().length == 0) { $("#objectB").hide(); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jqu ...

"Swift's JSON includes keys enclosed in quotation marks as well as keys without

When retrieving JSON data remotely and using SwiftyJson in Swift, I encountered an issue. Here is an example of the JSON object: { id = 3642; name = "Test"; "front_image" = "/image/dasad.jpg"; "is_new" = 0; price = "100"; } The proble ...

Discovering the technique to unearth a specific value within an array nested within another array

I am encountering an issue with finding a value in one array inside another array and utilizing the resulting value to update the state using setState(). Here is the initial state: this.state = { initialStudents:[ {name:"str1",tags;["str","s ...

Vue dynamic components fail to re-render within a v-for loop upon data changes

I've created a dynamic table component that allows me to modify columns by changing their ordering, adding new ones, or removing existing ones. The structure of my table body is as follows: <tr v-for="row in data" :key="row.id"& ...

Removing HTML tags from a string while preserving specific tags in JavaScript

Here is a JavaScript string that I am working with: var test = "<p>test</p> FOLER.PRODUCTS<12345><level-2>"; I'm trying to remove the HTML tags from the string because the service I'm using doesn't accept them. Here ...

Utilizing the ajaxForm plugin within a view that is generated as an AJAX response

As I develop a messaging system for my website, I have implemented a flat mailbox design. This means that accessing the inbox or composing a new message does not navigate to a different page; instead, it toggles between div elements. When a user clicks on ...

Showing a notification on the screen upon redirection to the index page

On my main index page, there are 18 divs representing different books. When a user clicks on a div, they can see details about the book such as title, author, and summary. There's also an option to add the book to a Collections array by clicking the " ...

Issues encountered while sending HTML Form data to MySQL with Node JS

I have been experimenting with a basic html form to mysql using nodejs, but unfortunately it is not functioning as expected. The HTML file is named index.html and the Node.js file is called test.js. Below you can find my code: My HTML <!DOCTYPE html&g ...

Is submitting data through ajax giving you trouble?

As a beginner in PHP with no knowledge of Javascript, I have been relying on tutorials to complete my JS tasks. Despite trying various solutions from StackOverflow, I have yet to achieve success! My goal is to update database values by clicking the ' ...

I'm having trouble removing an element from an array. The splice() method doesn't seem to be working properly

I start by creating an array like this: let myArray = []; Next, I add Number elements to the array: myArray.push(myNumber); When I call myArray.toString(), the array looks like this: 1,4,3,9 I have been attempting to remove certain elements using t ...

Converting Django forms into JSON format

Currently, I am attempting to convert my form data into JSON format within my view: form = CSVUploadForm(request.POST, request.FILES) data_to_json={} data_to_json = simplejson.dumps(form.__dict__) return HttpResponse(data_to_json, mimetype='applicati ...

Use Picasso to loop through and display images within an image set

Here is a sample of my .json file: { "0": { "image_path": "192.168.1.52/test/image/im1.jpg", "title": "image 1" }, "1": { "image_path": "192.168.1.52/test/image/im2.jpg", "title": ...

Encountering a client-side exception while deploying Next.js with react-google-maps/api on Vercel

Everything was running smoothly with my next js app during development and build phases. However, upon trying to deploy it on Vercel, I encountered an error when calling the page that uses my mapView component: An application error has occurred: a client- ...

method for assigning nested object values using an array of JSON objects

Here is the model class that I have: public class SearchForFlight { public SearchForFlight() { Segments = new otherType(); } public int AdultCount { get; set; } public JourneyType JourneyType { get; set; } public string Sou ...

Elevate the index of the name attribute for an input field within a dynamically generated form

In my scenario, I have created a form that includes indexed input fields for username and level: <form> <table> <tr class="trToClone"> <td> <label>Username:</label> <input type="text" name="usernam ...

Managing the triggering of the automatic transition in view models

My question is straightforward and requires no elaborate explanation. Can Durandal be configured to control the use of transitions when transitioning between viewmodels? The motivation behind wanting to disable the animation is as follows: I have a sear ...

How can a node be added between two nodes based on an attribute condition?

Is there a jQuery function, or perhaps another library function, that allows for the insertion of a node (div) between two other nodes (divs) based on its attribute? For instance: Assume I have the following HTML code: <div value=111/> <div val ...

The ng-route directive is preventing me from accessing the HTML content

My attempt to navigate my navbar using angular js seems to be running into an issue where the content in the HTML file is not displaying as expected. I'm unsure of what might be causing this problem. Here is the register page where both register and ...

Incorrect date formatting is being displayed

vr_date :Date alert(this.vr_date ) // Result Displays Thu Feb 07 2019 00:00:00 GMT+0400 var json = JSON.stringify(this.vr_date); alert(json); // Outcome Reveals 2019-02-06T20:00:00.000Z with incorrect date The date output shows 06 instead of 07 on my ...