Utilize JavaScript to refine an array of orders and utilize the PUT method to update the selected orders

I am struggling to find a way to filter and update the API on the filtered orders:

While working in the Shopify orders panel, I made an API call to retrieve a list of all orders. I managed to update one array using the put method, but it's not dynamic. Essentially, what I'm attempting to do is:

By the way, this is all written in JavaScript.

First, make a GET api call for all orders, then filter out the orders that have BOTH Canada as the country and a blank phone number. After isolating those specific orders, which meet the criteria of being from Canada with a blank phone number, I attempted to use the PUT method to change the phone number to "dummy number." However, I encountered difficulty applying this operation solely to those orders meeting the specified conditions. Initially, I retrieved all the orders, resulting in an array of 6 order objects. Below is my current code:


   $(document).ready(function () {
// Valid URL that returns all orders
  var api_url = "https://($api-domain-bla-bla)/admin/api/2020-10/orders.json?status=any.json";

  $.ajax({
    url: api_url,
    contentType: "application/json",
    dataType: "json",
    success: function (result) {
      console.log(result);
//       Get all orders phone country
      let orders = result.orders;
      console.log(orders);
      for(let i = 0; i < orders.length;i++) {
        let phone = orders[i].shipping_address.phone;
        let country = orders[i].shipping_address.country;
//    Filtering them right away, but unsure how to create an array of filtered objects.
//    The if statement functions correctly
        if ( country === "Canada" && phone === '') {
            // Perform actions on these objects where the if statement holds true.
            let filteredOrder = orders[i].concat
            console.log(orderId);
            // A function with parameters of the filtered objects variable and the API PUT method to update 
            // the filtered orders/objects
            checkCountry(filteredOrder);
        }

      }

    },
  });
});

Results from console.log(result)

(API response with all orders)

function checkCountry(order) {
// Here I aim to update the orders with Canadian addresses and blank phone numbers by setting the phone 
 // number to "00000"
    var api_url_post = "https://($api-domain-bla-bla)/admin/api/2020-10/orders.json?status=any.json";
    // This phone object has a similar structure to what I received from the earlier call, not sure 
    // why it's not being accepted.
    var phone = {
        "orders": 
          {
          "shipping_address": {
          "phone": "0000000000"
          }
          },
      }
    $.ajax({
          method: "PUT",
          url: api_url_post,
          contentType: "application/json",
          crossDomain: true,
          dataType: "json",
          data: JSON.stringify(phone),
          success: function (data, status, jqXHR) {
              alert("success");// write success in " "
          },
  
          error: function (jqXHR, status) {
              // Error handler
              console.log(jqXHR);
              alert('fail' + status.code);
          }
       });
}
 

Apologies if my explanation is unclear, any assistance would be appreciated?

Answer №1

I am uncertain of the objective you are aiming for. From what I gather:

  1. You are requesting an API to retrieve a list of orders.
  2. You wish to filter out Canadian orders without phone numbers from that list.
  3. You intend to modify the filtered list by adding dummy phone numbers and sending these changes to the server.

My knowledge of the API for retrieving/submitting orders is limited, so my approach may not be the most efficient. One idea could be to iterate over all orders and update those from Canada without a phone number:

orders = orders.map(order=>{
  let {country, phone } = order.shipping_address
  if(country === "Canada" && phone === ''){
    order.shipping_address.phone = '0000000'
  }
  return order
})

Instead of submitting only the filteredOrders, submit all orders:

$.ajax({
          method: "PUT",
          url: api_url_post,
          contentType: "application/json",
          crossDomain: true,
          dataType: "json",
          data: JSON.stringify(orders),
          success: function (data, status, jqXHR) {
              alert("success");// write success in " "
          },
  
          error: function (jqXHR, status) {
              // error handler
              console.log(jqXHR);
              alert('fail' + status.code);
          }
       });

There might be a more targeted way to update each qualifying order, but it depends on the specifics of the API you're using.

Answer №2

    $(document).ready(function () {
  var api_url = "https://api-blalbla/admin/api/2020-10/orders.json?status=any.json";

  $.ajax({
    url: api_url,
    contentType: "application/json",
    dataType: "json",
    success: function (result) {
      console.log(result);
//       get all orders phone country
      let orders = result.orders;
      console.log(orders);
      orders = orders.map(order=>{
        let {country, phone } = order.shipping_address
        if(country === "Canada" && phone === ''){
        order.shipping_address.phone = '0000000'
        checkCountry(order, orders)
            console.log(orders);
            console.log(order);
        }
        else {
          return order
        }
      
        
        
})
    },
  });
});

function checkCountry(filteredOrder, allOrders) {
     
    var api_url_post = "https://api-blalbla/admin/api/2020-10/orders.json?status=any.json";
    
//     var phone = {
//         "orders": 
//           {
// //               "id": 1843613401136,
// //               "phone": "+0000000000",
//                  "shipping_address": {
//                  "phone": "0000000000"
//           }
//           },
//       }
    $.ajax({
          method: "PUT",
          url: api_url_post,
          contentType: "application/json",
          crossDomain: true,
          dataType: "json",
          data: JSON.stringify(allOrders),
          success: function (data, status, jqXHR) {
              alert("success");// write success in " "
          },
  
          error: function (jqXHR, status) {
              // error handler
              console.log(jqXHR);
              alert('fail' + status.code);
          }
       });
            
}

This is the code I've been working on. All orders are retrieved from the API and filtered based on specific criteria like country and phone number. If both conditions are met, the phone number is updated to '0000000'. There seems to be an issue with the PUT request, but I'm troubleshooting it.

Link to screenshot for reference

I also discovered that individual orders can be accessed using their ID:

/admin/api/2020-10/orders/{order_id}.json

So, my plan is to retrieve the filtered order ID and update its phone number to "00000" by passing it as a parameter in the URL. Do you think this approach will work?

Answer №3

Yes, that method actually worked perfectly for me

After some experimentation, I discovered that it is possible to retrieve a specific order by its id

/admin/api/2020-10/orders/{order_id}.json
So maybe I can input the filtered order id as a parameter in the URL and update that particular order with the phone number "00000". Do you think this approach will be successful?

I truly appreciate your help, this code snippet has been incredibly useful to me! :)

   orders = orders.map(order=>{
  let {country, phone } = order.shipping_address
  if(country === "Canada" && phone === ''){
    order.shipping_address.phone = '0000000'
  }
  return order
})

Answer №4

UPDATE: Can I retrieve only the initial order from the array?

// Maybe extract first order using .map to [0]
orders = orders[0](order=>{
  let {country, phone } = order.shipping_address
  if(country === "Canada" && phone === ''){
    order.shipping_address.phone = '0000000'
  }
  return order
})

I specifically require this functionality to optimize performance when dealing with a large number of orders (e.g., 20k). It will only process the first order, which is typically the latest one created.

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

timings and pauses utilizing JavaScript

Currently, I am facing a challenge while working on a Simon Says game. My struggle lies in the part where I need to illuminate the buttons that the user has to click. I am using a "for" loop to iterate through each element in the array where I have stored ...

Highlight.js is not able to display HTML code

It's strange, I can't seem to get the HTML code to display correctly. This is my HTML: <head> <link rel="stylesheet" href="/path/to/default.css"> <script src="/path/to/highlight.pack.js"></script> <script& ...

Unable to transfer errors from API response to Formik error display

I am currently using React, Formik, and yup to send data to a REST API. This is the structure of my React component: import React from "react"; import { render } from "react-dom"; import { Formik, Field, Form, ErrorMessage } from "formik"; import * as ...

Issue with fgetcsv() not properly handling newlines during conversion of CSV file to array

My data consists of airport codes and city names in an array with around 3500 lines. code,city "Abilene, TX ",ABI "Adak Island, AK ",ADK "Akiachak, AK ",KKI "Akiak, AK ",AKI "Akron/Canton, OH ",CAK "Akuton, AK ",KQA "Alakanuk, AK ",AUK "Alamogordo, NM ",A ...

Retrieve JSON data from a RESTful API by utilizing pure javascript

I'm eager to try out the Wikipedia search API in JavaScript, even though it might be simpler with jQuery. I want to make sure I understand the basics first before turning to frameworks. Below is the code I've come up with, but for some reason, I ...

Attain worldwide reach

I'm currently facing a Scope issue that has been quite challenging to resolve. The saying goes, "a picture is worth a thousand words," and in this case, it couldn't be more true. Whenever the OK or REJ buttons trigger the reject() function, passi ...

Setting up a plan for executing Javascript server side scripts

Can JavaScript be executed server-side? If I attempt to access a script , can it be scheduled to run every four hours? Would most web hosts allow this, or is it considered poor webmaster practice? The main goal is to activate my website's webcrawler/ ...

Automated HTML Slideshow Feature

I am currently working on creating an automated slideshow that spans the entire page and switches images every 4 seconds. I have set up a codepen for testing purposes, but I am encountering some issues with it. There are 5 images that I am using, and my g ...

Utilizing qTip2 and Knockout.js for enhanced binding functionality

I have a situation where I am utilizing qTip2 to show validation errors on input fields. In certain scenarios, a group of input fields is hidden using knockout.js 'visible' binding. Despite being hidden, the qTip2 tooltips attached to these input ...

Attempting to analyze a JSON string within the vicinity in order to execute a specific function

Currently, I am integrating a local JSON file to simulate an API connection in my project. The challenge I am facing is related to accessing the image key within the products of the JSON data. In my project setup, I have images that are imported using stat ...

How can I create the effect of text changing color automatically after a specified time period has elapsed

I am currently dealing with a timer that is functioning properly, but I have a specific CSS inquiry. Essentially, what I would like to achieve is when the timer hits 30 seconds, I want the numbers to change to red color. $(function () { var $startTimer = ...

Utilize Vuex mutators within route navigation guards

Hey there, I'm currently working on an app using Laravel and VueJS. To restrict certain routes, I've implemented navigation guards. However, I'm facing an issue where I need to access Vuex mutators to determine if the current user is logged ...

Having trouble setting up react-i18n with hooks and encountering a TypeError: Cannot read property '0' of undefined?

Encountering an error while setting up the react-i18n with hooks: TypeError: Cannot read property '0' of undefined Here's the content of i18n.js: import i18n from 'i18next'; import { initReactI18next } from 'react-i18next/h ...

Loading a directive before the page loads in Vue.js

In my application, I've implemented a directive that dynamically displays buttons based on the user's role permissions: import { store } from '../store/'; import * as types from '../store/types'; const hide = vnode => { ...

The react-bootstrap implementation is not functioning as expected, resulting in an unsupported server component error

Having an issue with an Unsupported Server Component Error while using react-bootstrap with typescript. I've shared the contents of my page.tsx file, layout.tsx file, and the specific error message. layout.tsx file import type { Metadata } from &apos ...

React Navigation Error: navigateTo must be used within a valid router configuration

When attempting to utilize useNavigation() from react-router-dom, I encounter the following error: Error: useNavigation must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router. NavBar src/components/NavBar.js:6 3 ...

Ways to prevent endless recurrence in callback functions

I've been struggling to figure out why I keep encountering an infinite recursion issue within the Vue's Vue-charts legendCallback, and I haven't been able to find a solution. Any help would be greatly appreciated. Within my Vue component, t ...

Display the closest locations on the Google Maps interface

I am currently working on a project that involves integrating Google Maps. The project includes storing hospital addresses (in longitude and latitude) in a database. However, I need assistance in displaying the nearest hospital from my current location. I ...

Initiate navigation in AngularJS through routing

My AngularJS app has a reset link that I need to use to reset it... <a ng-click="resetApp()">reset</a> The button press is being handled in the main controller... $scope.resetApp = function(){ if(confirm("You will lose data...")){ ...

Introduction to Angular controller binding for beginners

I'm currently going through this tutorial : http://www.youtube.com/watch?v=i9MHigUZKEM At 46:32 minutes into the tutorial, this is the code I have implemented so far : <html data-ng-app="demoApp"> <body data-ng-controller="SimpleControlle ...