Destructuring arrays of objects in ES6 with conditions

Check out the demo on stackblitz: here

The scenario is this: the server responds in a specific format, and based on certain conditions, we need to determine whether to show or hide buttons on a page. Each button has its own click function, which is why the buttons are statically declared on the page.

We have an array of objects with properties that need to be mapped to other properties under certain conditions.

collections = [
  {
    "productId": "samsung",
    "productParams": "",
    "isAvailable": true
  },
  {
    "productId": "nokia",
    "productParams": "",
    "isAvailable": true
  },
  {
    "productId": "Lg",
    "productParams": "",
    "isAvailable": false
  },
]

Within this collection array, I am attempting to map the object's properties based on two conditions:

If the value of productId matches a specific string and the isAvailable property is set to true, I assign it to a global variable to show the respective button. However, there seems to be an issue with the code logic. Can someone help me identify what I did wrong?

getClick() {
  let showButtonSamsung, showButtonNokia, showButtonLg;
  let x = this.collections.map(x => {
    showButtonSamsung = x.productId == 'samsung' && x.isAvailable == true ? true : false;
    showButtonNokia = x.productId =='nokia' && x.isAvailable == true ? true : false;
    showButtonLg = x.productId == 'Lg' && x.isAvailable == true ? true : false;
  });
}

Expected Output:

showButtonSamsung: true // will show the button
showButtonNokia: true // will show the button
showButtonLg: false // hide the button

Answer №1

I believe utilizing the reduce method would offer a more efficient solution in this scenario.

let items = [{
    "productId": "apple",
    "productParams": "",
    "isAvailable": true
  },
  {
    "productId": "google",
    "productParams": "",
    "isAvailable": false
  },

  {
    "productId": "microsoft",
    "productParams": "",
    "isAvailable": true
  }
]


const mappings = {
  apple: "displayApple",
  google: "displayGoogle",
  microsoft: "displayMicrosoft"
}

const {displayApple, displayGoogle, displayMicrosoft} = items.reduce((accumulator, object) => {
  const property = mappings[object.productId];
  accumulator[property] = object.isAvailable;
  return accumulator;
}, {})

console.log(displayApple, displayGoogle, displayMicrosoft);

Answer №2

Here is a code snippet that may meet your requirements:

 const collections = [
    {
        "productId": "samsung",
        "productParams": "",
        "isAvailable": true
    },
    {
        "productId": "nokia",
        "productParams": "",
        "isAvailable": true
    },

    {
        "productId": "Lg",
        "productParams": "",
        "isAvailable": false
    }];

let isAvailable = (brand, collections) => collections.some((x) => x.productId === brand && x.isAvailable) 

let x = {
    showButtonSamsung: isAvailable('samsung', collections),
    showButtonNokia: isAvailable('nokia', collections),
    showButtonLg: isAvailable('Lg', collections),
}
console.log(x);

Alternatively:

let x = {
    showButtonSamsung: 'samsung',
    showButtonNokia: 'nokia',
    showButtonLg: 'Lg',
}


let isAvailable = (brand, collections) => collections.some((x) => x.productId === brand && x.isAvailable)
x = Object.entries(x).map(([key, value]) => ([key, isAvailable(value, collections)]))
    .reduce((obj, arr) => ({
        ...obj, [arr[0]]: arr[1]
    }), {})

console.log(x);

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

The button event is currently only targeting the initial class. (Jquery)

I am having an issue where only the first instance of the saveBtn class is being saved into local storage when clicked. Can anyone provide some assistance with this? Here is the HTML: <div class="hour-container" id="8am"> & ...

Interactive grid feature created with HTML Canvas

Imagine my surprise when I discovered that the latest version of Google Spreadsheets is now using a canvas tag to render the spreadsheet grid, unlike the traditional <table><tr><td> method used in the past. In the previous version, only ...

Highcharts revolutionizing the way data is displayed with real-time data integration in 202

Struggling with an ajax request that should return a datetime array for use in highcharts. The data is coming back as a json array like this: [[1395489600000,29.010971409934],[1395493200000,29.234899961948],[1395496800000,29.712949994206],[1395500400000,2 ...

My goal is to create a map and store its data in an array called "rows." This array will then be utilized in a DataGrid component from material-ui

However, when I run a console.log(rows), it returns an undefined list. let rows: Array<{ id: number }> = [] rows = products?.map((product) => { id: product.product_id } ) Attempting to do it without using map does work, like so: let rows = [ ...

The feature of "compile on save" is not functioning properly in my current Angular project

Yesterday I used the angular cli (ng new my-app) to create a new project, but unfortunately the "compile on save" option is not functioning properly. Interestingly, I have two projects on my computer and this feature works fine for one of them but not for ...

Is the XMLHttpRequest.onreadystatechange event still triggered behind the scenes when Promises are utilized?

Imagine I am utilizing a Promisified API for executing an Ajax Request, would the event-loop still resort to calling the basic XMLHttpRequest.onreadystatechange? Although using Promisfying enables coding in a sequential manner, essentially it is still rel ...

Automated tasks running on Firebase Cloud Functions with cron scheduling

There are two cloud functions in use: The first cloud function is used to set or update an existing scheduled job The second one is for canceling an existing scheduled job The management of scheduling jobs is done using import * as schedule from &ap ...

Encountering an error while trying to update a field using the $inc operator in

Currently, I am working on updating a field in my database to increment it each time like a counter. This will allow me to consistently receive the latest values. To achieve this, I have defined the following schema: var CounterSchema = new Schema({ _id: ...

Add the list of information during the looping process (map)

I am currently facing a challenge where I need to update my data during the iteration and send the results to an API call. The API Call expects a request with data structured in the following format: { list: [{ id: "1", name: "Hello" ...

Navigating to a URL using "res.render" following the process of fetching POST data from the DOM array in Node.js

Despite browsing through numerous related questions, I am still unsure about the best approach to render a URL after the frontend JavaScript collects DOM data and sends a POST request to an Express server's POST URL. I understand that fetch POST does ...

Steps to access a Request object within a Controller

I am currently working with Express and Typescript, utilizing Controllers for managing requests. In an attempt to create a BaseController that includes the Request and Response objects for each request, I wrote the following code snippet. However, it see ...

There was an issue with the second level object in the response from the Node.js

Here's the scenario I'm dealing with: app.post('someUrl', function (req, res) { var r = res.data; var a = {}; a.name = r.name || ""; a.someotherKey : { id: r.otherKey.id || "" } }); The issue arises when ...

Angular 2 - The creation of cyclic dependencies is not allowed

Utilizing a custom XHRBackend class to globally capture 401 errors, I have encountered a dependency chain issue in my code. The hierarchy is as follows: Http -> customXHRBackend -> AuthService -> Http. How can this problem be resolved? export cla ...

Guide on incorporating arrays into an array using JavaScript

Is there a way to achieve the specified outcome in JavaScript? I attempted to find a method for it on MDN but was unsuccessful. let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { for (b = 1; b <= 3; b++) { allNumbers.push(a ...

Extracting information from JSON fixture within simulated Angular service

I recently developed a mock Angular service specifically for testing a controller. However, whenever I run my tests, an error pops up saying: Unexpected request: GET ./fixtures/stats.json. This is how the code looks like in mock.players.service.js: &apos ...

What is the benefit of storing an IIFE in a variable?

When it comes to using IIFE in JavaScript and AngularJS, I have come across two common structures: Structure 1: //IIFE Immediately Invoked Function Expression (function () { }()); However, there is another structure where the IIFE is assigned to a var ...

Transform the Asp.net JavaScript jsgantt-improved Gantt chart to be compatible with Blazor

Struggling to implement a Gantt chart in Blazor with razor pages after finding a nice one for Asp.net. Any tips on how to proceed? I've already added jsgantt.js and jsgantt.css to wwwroot and included references in index.html. But now, how do I go a ...

Trigger an event in Angular using TypeScript when a key is pressed

Is it possible to activate a function when the user presses the / key in Angular directly from the keydown event? <div (keydown.\)="alerting()"> </div> <div (keydown.+)="alerting()"> </div> Both of these ...

"Having issues with Django not properly applying the JavaScript and CSS files I've linked in

I have completed my project and organized all the necessary files, including index.html, css, js, and settings.py within the appropriate folders. I am encountering an issue with applying a pen from the following source: CodePen index.html <!DOCTYPE h ...

What is the best method for determining the input values based on the changing range slider values?

Having some jquery issues currently. I am utilizing an ionrange slider to retrieve values, and then I need to apply conditions using if else statements (around 5-7 conditions) based on these values and display them in another input field. However, the desi ...