Creating an array of objects using a constructor: a step-by-step guide

a) Here is an example of an array containing objects with various properties:

[
    {
        "Account": "1111-000",
        "Desc": "Accrued - Payroll & Payroll Tax",
        "Amount": "-8,459.88",
        "Partner": "RAP",
        "FY": "2018",
        "PD": "10",
        "VNO": "abc"
    },
    {
        "Account": "2222-000",
        "Desc": "Accrued - Management Fee",
        "Amount": "-9,228.33",
        "Partner": "RAP",
        "FY": "2018",
        "PD": "10",
        "VNO": "dfe"
    },
    {
        "Account": "3333-000",
        "Desc": "Current Year Earnings",
        "Amount": "0",
        "Partner": "RAP",
        "FY": "2018",
        "PD": "10",
        "VNO": "bcd"
    },
]

b) To create a specific output based on the values from each object, I plan to iterate through the array and use a constructor function as follows:

gridinsert: [{
  value: "1111-000",
  command: "setGridValue",
  columnID: "17"
}, {
  value: "Accrued-Payroll & payroll tax",
  command: "setGridValue",
  columnID: "18"
}, {
  value: "-8,459.88",
  command: "setGridValue",
  columnID: "19"
}, {
  value: "RAP",
  command: "setGridValue",
  columnID: "20"
}, {
  value: "2018",
  command: "setGridValue",
  columnID: "12"
}, {
  value: "10",
  command: "setGridValue",
  columnID: "21"
}, {
  value: "abc",
  command: "setGridValue",
  columnID: "23"
}]

Since the JSON data maintains a consistent order, I can easily extract values and format them into separate objects within the gridinsert:[] structure for each original object.

Answer ā„–1

Is this the desired format you are searching for?

Each input element is linked to an output element with a characteristic gridinsert which consists of an array of elements created from each property in the input element.

The column identifiers are correlated to the property names utilizing an object:

const colIDs = {
  Account: 17,
  Desc: 18,
  Amount: 19,
  Partner: 20,
  FY: 12,
  PD: 21,
  VNO: 23
};

If the keys are inconsistent, for example, if there is a mix of uppercase or lowercase keys and potential mistakes in some keys, convert all keys to lowercase and insert entries for common errors or synonymous keys. Before using the map by key, ensure to convert the key to lowercase.

const colIDs = {
  account: 17,
  desc: 18,
  description: 18, // alternative to desc
  amount: 19,
  quantity: 19, // use this instead of amount
  partner: 20,
  fy: 12,
  pd: 21,
  vno: 23
};

The correlation is carried out through Object.entries and map:

const result = data.map(elem => ({
    gridinsert: Object.entries(elem).map(([key, value]) => ({
       value,
       command: 'setGridValue',
       columnID: colIDs[key.toLocaleLowerCase()]
     }))
}));

Here is an illustration:

const data = [{
    "account": "1111-000",
    "Desc": "Accrued - Payroll & Payroll Tax",
    "amount": "-8,459.88",
    "Partner": "RAP",
    "FY": "2018",
    "PD": "10",
    "VNO": "abc"
}, {
    "Account": "2222-000",
    "Description": "Accrued - Management Fee",
    "Amount": "-9,228.33",
    "Partner": "RAP",
    "FY": "2018",
    "PD": "10",
    "VNO": "dfe"
}, {
    "Account": "3333-000",
    "Desc": "Current Year Earnings",
    "Amount": "0",
    "Partner": "RAP",
    "FY": "2018",
    "PD": "10",
    "VNO": "bcd"
}];

const colIDs = {
  account: 17,
  desc: 18,
  description: 18,
  amount: 19,
  quantity: 19,
  partner: 20,
  fy: 12,
  pd: 21,
  vno: 23
};

const result = data.map(elem => 
    Object.entries(elem).map(([key, value]) => ({
       value,
       command: 'setGridValue',
       columnID: colIDs[key.toLocaleLowerCase()]
    })
));

console.log(result);

To compile all transformed properties of your input entities into a single array, you can follow this approach:

const result = data.reduce((acc, elem) => {
    const entries = Object.entries(elem).map(([key, value]) => ({
       value,
       command: 'setGridValue',
       columnID: colIDs[key.toLocaleLowerCase()]
     }));
    acc = [...acc, ...entries];
    return acc;
}, []);

However, employing this method may lead to conflicts between properties that have identical values.

const data = [..]; // same data as above

const colIDs = {..}; // same colIDs as above

const result = data.reduce((acc, elem) => {
  const entries = Object.entries(elem).map(([key, value]) => ({
     value,
     command: 'setGridValue',
     columnID: colIDs[key.toLocaleLowerCase()]
   }));
  acc = [...acc, ...entries];
  return acc;
}, []);

console.log(result);

Answer ā„–2

One approach to tackle this issue is by creating a mapping between object keys and the corresponding columns ids. This can be achieved as follows:

const keyValueMapping = {
    "Account": "17",
    "Desc": "18",
    "Amount": "19",
    "Partner": "20",
    "FY": "12",
    "PD": "21",
    "VNO": "23"
}

You can then utilize the reduce() function on your array to generate the desired outcome:

const data = [
    {
        "Account": "1111-000",
        "Desc": "Accrued - Payroll & Payroll Tax",
        "Amount": "-8,459.88",
        "Partner": "RAP",
        "FY": "2018",
        "PD": "10",
        "VNO": "abc"
    },
    {
        "Account": "2222-000",
        "Desc": "Accrued - Management Fee",
        "Amount": "-9,228.33",
        "Partner": "RAP",
        "FY": "2018",
        "PD": "10",
        "VNO": "dfe"
    },
    {
        "Account": "3333-000",
        "Desc": "Current Year Earnings",
        "Amount": "0",
        "Partner": "RAP",
        "FY": "2018",
        "PD": "10",
        "VNO": "bcd"
    }
];

const keyValueMapping = {
    "Account": "17",
    "Desc": "18",
    "Amount": "19",
    "Partner": "20",
    "FY": "12",
    "PD": "21",
    "VNO": "23"
}

let gridInsertsArray = data.reduce((accumulator, object) =>
{
    let gridInsert = [];

    Object.keys(object).forEach(
        key => gridInsert.push({
            value: object[key],
            command: "setGridValue",
            columnID: keyValueMapping[key]
        })
    );    

    return [...accumulator, gridInsert];
}, []);

console.log(gridInsertsArray);

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

What is the best way to handle a nested list() that arises while parsing JSON files in R?

Having multiple JSON files that need to be read and combined in r, each containing data for 51 observations. However, upon reading the JSON file in r, the required information is nested within the "mentions" column. The goal is to extract the time stamp fr ...

Tips to prevent modal impacts on underlying elements?

When I click on a button, a modal pops up. However, the background contents seem to spread out and sometimes scroll automatically when the modal appears. I have searched for a solution to this issue but have been unsuccessful. Can anyone please help me ide ...

What is the best way to substitute a character in a string with a specific text?

Looking to create a function that automatically replaces characters in a string with specified values. For example: let word = 'apple'; replaceValues(word); function replaceValues(value) { //Need to replace the characters 'a', &apo ...

What is the best way to convert a multi-line result into a JSON format?

I'm having trouble encoding my query results into a JSON format. It seems to fail when the query returns more than one result, but works fine when there is only one result. if (isset($_REQUEST['query'])) { $query = $_REQUEST['query ...

Disable the default page scrolling behavior when collapsing an accordion section in Bootstrap 4 framework

Incorporating a Bootstrap 4 accordion with an expanded body section that causes the content below to scroll up when collapsed. To address this issue, attempting to scroll to the top of the clicked header and prevent undesirable scrolling from the collapse ...

Troubleshooting Issue with InfoWindow Display on Multiple Markers in Google Maps

I'm having trouble getting my markers to show different infowindows. No matter what I do, the markers always display the content of the last "contentString" in the loop. Despite reading through multiple posts on this issue, I haven't been able t ...

How can I adjust the font size of material-ui buttons while ensuring that they scale appropriately?

Having trouble adjusting the font sizes on Material-UI's RaisedButton for React and ensuring that the button scales properly along with it. <RaisedButton label={<span className="buttonText">Log in Here</span>} /> CSS: .buttonText ...

Exploring the depths of web automation using Python and Selenium, harnessing the power of a while

Currently, I am navigating through various pages on iens website using Selenium and Python. My goal is to click on the "Volgende" button (which means "next" in Dutch) continuously until there are no more pages left by implementing a while loop. Specificall ...

Should you include the dollar sign in a Vue HTML variable or not?

Iā€™m a bit confused about whether or not I should include $ when using a Vue HTML variable: new Vue({ data: { a: "myData" } }); Do I need to use: <h1>My value is {{ a }}</h1> or <h1>My value is {{ $a }}</h1> What ...

Sending an array of functions to the onClick event of a button

Having difficulty with TypeScript/JavaScript Currently working with an array of functions like this private listeners: ((name: string) => void)[] = []; Successfully adding functions to the array within another function. Now looking to trigger those ...

Analyzing vast datasets from contrasting perspectives

Looking for a way to compare two different data storages that contain the same data. The data in question is: const object1 = { "name": "John", "age": "30", "height": "180 cm", "stand ...

What is the best way to generate the message dynamically?

I have implemented the react-intl package for translation purposes in my project. Users have the option to choose between Spanish and English languages, with Spanish being the default language. When a user switches to English, all text should be dynamicall ...

Setting up React Router in a nested directory with a flexible route structure

As a newcomer to react router, I am seeking guidance on setting it up in a specific scenario. Imagine we have a PHP application running on 'http://www.example.com'. Within this setup, there is a react application located at 'http://www.examp ...

Unable to determine the dimensions of the Kafka JSON message

My task involves sending a JSON message through Kafka, but my application has limitations on the size of messages it can handle. To construct the message, I am using a Python script. This script reads a base JSON from a file, transforms it, and then saves ...

What method can I use in webpage coding to achieve this special highlight effect, and what is the official term for it?

Need help figuring out how to make an icon change from blue to white when selected. I've searched through Bootstrap, CSS, and HTML, but haven't found the solution yet. Any suggestions would be appreciated! https://i.stack.imgur.com/RK1PD.png ...

Using Local Storage to store arrays in JavaScript/jQuery

Currently, I am implementing a set of multiple buttons each containing data-id and data-name Below is my concept along with some sample code for reference: $(".clickCompare").click(function ({ var id = $(this).attr('data-id'); var ...

I'm having trouble decoding the response from the Tweepy API in Python. Can anyone lend

Greetings to you and your loved ones. Thank you for taking the time to read this message, and I apologize if it is a duplication (please guide me to the correct place in that case!) I am currently exploring how to connect with the Twitter API using Tweepy ...

Set the height of a div based on the height of another div

My challenge involves a textarea that dynamically expands as content is added to it. The structure of the textarea within a div element is illustrated below: <div id='sendMes' class='container-fluid'> <form action='#&apos ...

Retrieving Article URL from JSON Object in C# - A Step-by-Step Guide

Utilizing NewsAPI to retrieve relevant articles has presented a challenge for me, primarily due to the return type being in JSON object format. Having limited experience working with JSON objects, I found that the provided answers were often too specific a ...

Adding data to an AngularJS template

I am encountering an issue with a flag that I am toggling between true and false to alter the display of certain elements on my page. While it works outside of the template, integrating this value into the template itself has proven challenging. restrict: ...