Changing Array Object into a different Array Object (with Angular)

I am dealing with an array Object

[
{ product: "Product A", inStock: 3, onHold: 1, soldOut: 2 },
{ product: "Product B", inStock: 2, onHold: 0, soldOut: 1 }]

I am struggling to convert it into the new array format below. Any assistance would be greatly appreciated

[
{ inStock: 1, product: "Product A" },
{ inStock: 1, product: "Product A" },
{ onHold: 1, product: "Product A" },
{ soldOut: 1, product: "Product A" },
{ soldOut: 1, product: "Product A" },
{ inStock: 1, product: "Product B" },
{ inStock: 1, product: "Product B" },
{ soldOut: 1, product: "Product B" },

]

If the onHold value is 0, it should not appear in the new array

Answer №1

To achieve this, utilize the `reduce` function and within the callback, iterate over the current object to check if the value of the current key is a number and greater than 0.

let data = [{
    testName: "Test system",
    in: 2,
    low: 1,
    medium: 2
  },
  {
    testName: "Test app",
    in: 2,
    low: 1,
    medium: 0
  }
];

var result = data.reduce(function(acc, obj) {
  for (const key in obj) {
    if (!isNaN(obj[key]) && obj[key] > 0) {
      for (var i = 0; i < obj[key]; i++) {
        acc.push({testName: obj.testName, [key]: 1});
      }
    }
  }
  return acc;
}, []);
console.log(result)

Answer №2

const data = [
    { title: "Software A", inStock: 2, lowStock: 1, mediumStock: 2 },
    { title: "App B", inStock: 2, lowStock: 1, mediumStock: 0 }]

let createNewItem = (_item, _category) => {
    const newItemArray = []
    for(let i = 0; i < _item[_category] || 0; i++){
        let newItem = {}
        newItem[_category] = 1
        newItem["title"] = _item["title"]        
        newItemArray.push(newItem)
    }
    return newItemArray;
}
newItemList = [];
data.forEach( (_item) => {
    ["inStock", "lowStock", "mediumStock"].forEach((_category) => {
        newItemList.push( ...createNewItem(_item, _category) )
    })
})
console.log(newItemList)

Answer №3

This question is more focused on JavaScript/TypeScript concepts rather than Angular-specific topics.

const data = [
  { targetName: "System A", in: 2, low: 1, medium: 2 },
  { targetName: "App X", in: 2, low: 1, medium: 0 },
];

data.reduce((finalResult, currentItem) => {
  const properties = Object.keys(currentItem).filter((property) => property !== "targetName");
  const additionalItems = properties.reduce((responseArray, property) => {
    let itemsToAdd: Record<string, string | number>[];
    for (let i = 1; i <= currentItem[property]; i++) {
      [...itemsToAdd, { [property]: 1, targetName: currentItem.targetName }];
    }
    return !!itemsToAdd ? [...responseArray, ...itemsToAdd] : responseArray;
  }, [] as Record<string, string | number>[]);
  return [...finalResult, ...additionalItems];
}, [] as Record<string, string | number>[]);

Answer №4

No one has attempted the flatMap method yet, so here is my solution:

   const list = [
  {
    testTargetname: 'Test system',
    in: 2,
    low: 1,
    medium: 2
  },
  {
    testTargetname: 'Test app',
    in: 2,
    low: 1,
    medium: 0
  }
]

const newList = list.flatMap((currentItem) => {
  const targetKey = 'testTargetname'
  return Object.entries(currentItem)
    .filter(([key]) => key !== targetKey)
    .map((item) => {
      const obj = Object.fromEntries([item])
      return {
        ...obj,
        [targetKey]: currentItem[targetKey]
      }
    })
})

console.log(newList)

Just a heads up, this example demonstrates how it can be mapped to the correct structure. If you need to filter specific values, you can simply use the filter function at the end.

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 there a similar alternative to {useLocation} provided by 'react-router-dom' that can be used in Next.js?

import { useLocation } from 'react-router-dom'; Currently utilizing Nextjs, I'm seeking assistance in finding an alternative for useLocation ` import Link from 'next/link'; import { FC } from 'react'; import {useRout ...

How to iterate through properties declared in an Interface in Angular 12?

Before Angular 12, this functioned properly: export interface Content { categories: string[] concepts: Topic[] formulas: Topic[] guides: Topic[] } //this.content is of type Content ['formulas', 'concepts'].forEach(c =&g ...

Validation of AngularJS dropdown selection must be completed before submitting the form

I have a Dropdown list within my form and I want to disable the submit button until an element is selected from the list. Here is my button: <input type="submit" value="Get" ng-disabled="form.$invalid " /> I attempted to implement the solution foun ...

Troubleshooting a jQuery filter function selector issue

Here's a function I've created: $.fn.filterByClass = function(cls) { var o = $(this); return o.filter(function() { if ($(this).attr("class") == cls) { return $(this); } }); }; Let's say we have multiple fo ...

Retrieve data from a text file using ajax and then return the string to an HTML document

Just starting out with ajax, I have a text file containing number values For example, in ids.txt, 12345 maps to 54321 12345,54321 23456,65432 34567,76543 45678,87654 56789,98765 Here is the Html code snippet I am using <html><body> < ...

"Endowed with improper dimensions, the BootStrap collapse feature

Yesterday, I posted about an issue with BootStrap and panel collapsables causing graph sizes to become distorted. The post was locked because there was no accompanying code. I have now created a code snippet for you all to see the exact problem I am facing ...

Exploring the Inner Workings of a React ES6 Class Component

I'm currently exploring the best practices in React and I find myself questioning the structure of a React Component when utilizing ES6 classes. I am particularly interested in where to declare variables or properties that the class or .js file will u ...

Unable to retrieve options from a particular select box

Utilizing cheerio and nodejs to scrape all the countries listed on a website, I have implemented the following code: const rp = require('request-promise'); const cheerio = require('cheerio'); const options = { uri: 'https://u ...

Is it possible to send React props to the next/image within a component?

I need assistance with creating a card component that utilizes next's Image component. However, the src prop on Image is not accepting the props that I am passing down. import React from 'react' import { Childs } from '../../interfaces/ ...

"Encountered an error while trying to locate the view" in a simple Express.js application

Embarking on the journey to learn Express.js, I decided to create a simple Express app. The structure of my app.js is as follows: var express = require('express'); var app = express(); app.configure(function(){ app.set('view engine&ap ...

The program encountered an issue trying to change a string into a float value

In my Python script, I created 2 columns and converted them into an np array. Then, I successfully saved them in a new file. fi = np.array([co,pred[40]]) fi=fi.T np.savetxt("Pred_40.dat", fi, delimiter=" ") Now, my goal is to develop a ...

Express router parameter matching

Let's consider a scenario where I have two routes - one with parameters and one without: /foo?bar /foo I aim to assign different handlers for these routes. Instead of the conventional approach, I am looking for a way to simplify the code. app.use(&a ...

Continue perusing the Angular JS HTTP request

I'm currently delving into the world of web systems, still a bit green when it comes to Angular JS. The feature I'm tackling now requires a POST call using Angular. Implementing the POST call itself isn't too tricky in Angular. However, my ...

Sending an Array of Data to Jquery

One of the buttons in my code looks like this: <button id='abc' value=['fred', 26]></button> I am looking for a way to retrieve the two values using JQuery's .val() function. My attempt $("#abc").val()[0] only return ...

"Retrieve a list of all routes that have been registered in Node.js

I am trying to retrieve a list of all registered routes in my project. Here is the code I have used for this purpose: const app = require("express"); let routers = app._router.stack .filter((r) => r.route) .map((r) => { return { ...

Launching Angular Application on Amazon Web Services S3 or EC2

I'm currently looking into deploying an Angular application on AWS and I've come across two potential methods: Using an S3 Bucket Deploying on an EC2 instance with nginx Which of these options is considered the best approach and why? The appli ...

What could be causing my items to appear twice and as blank elements?

I'm feeling a bit lost here as to why my code isn't functioning correctly. For some reason, it's not displaying the predefined items that I've set up. Any guidance or assistance would be greatly appreciated. Dealing with Angular errors ...

Update the appearance of a cell if the value within it is equal to zero

I have discovered a way to achieve this using inputs. input[value="0"] { background-color:#F7ECEC; color:#f00;} Now, I am looking for assistance in applying the same concept to table cells. Can anyone provide guidance? Thank you. ...

How can I implement a view counter feature in a Vue application?

I am currently working on a Vue-based post website. One feature I want to add is the ability for users to see the number of views the post has received. Each time a user clicks on a post, the view count should increase by 1. I am utilizing Firebase as m ...

Dynamically loading classes in TypeScript without using default export

Is there a way to dynamically load classes in TypeScript without using a default export method? I have managed to make it work partly, but I am looking for a solution that doesn't require a default export: export default class Test extends Base { ... ...