Javascript- Retrieving information from an array containing various objects

Struggling with extracting data from another object.

The information provided is not in English, but that shouldn't be an issue.

[
  {
    productName: 'Data Sharer',
    itemNumber: 'TESZOR 61.20.42',
    unit: 'month',
    quantity: 1,
    netUnitPrice: '543.30',
    netPrice: '543.30',
    vatRate: 5,
    vatValue: '27.16',
    grossPrice: '570.46',
    id: 1,
  },
  // more data arrays...
];

The problem arises when attempting to extract the data under "productName"

[  "Data Sharer",  null,  null,  "Car Card" ]

I suspect the issue lies within the nested array causing unexpected "null" values, but I have been unable to resolve it after multiple attempts.

Any assistance would be greatly appreciated!

Answer №1

Flat as a Pancake

In case you're not interested in preserving the nested arrays, don't worry! You can flatten out the outer array using Array#flat() and then apply a map() function to extract the desired property.

const input = [{ termeknev: 'Adatmegosztó', besorszam: 'TESZOR 61.20.42', mennyegys: 'hó', menny: 1, nettoegysegar: '543,30', nettoar: '543,30', afakulcs: 5, afaertek: '27,16', bruttoar: '570,46', id: 1, }, ...];

const termeknevFlat = input.flat().map(({ termeknev }) => termeknev);
console.log('Flat as a Pancake:', termeknevFlat);

Nested (known Depth)

If you fancy maintaining the nested arrays with a known depth of only 2 levels, you can hop on board with nested map() calls.

const input = [{ termeknev: 'Adatmegosztó', besorszam: 'TESZOR 61.20.42', mennyegys: 'hó', menny: 1, nettoegysegar: '543,30', nettoar: '543,30', afakulcs: 5, afaertek: '27,16', bruttoar: '570,46', id: 1, }, ...];

const termeknevNested = input.map(o =>
  Array.isArray(o)
    ? o.map(({ termeknev }) => termeknev)
    : o.termeknev
);
console.log('\nNested (known Depth):', termeknevNested);

The Never-Ending Story (Arbitrary Depth)

If the nesting plunges into infinite depths, fear not! Craft a recursive map function that embraces callbacks like an old friend.

const input = [{ termeknev: 'Adatmegosztó', besorszam: 'TESZOR 61.20.42', mennyegys: 'hó', menny: 1, nettoegysegar: '543,30', nettoar: '543,30', afakulcs: 5, afaertek: '27,16', bruttoar: '570,46', id: 1, }, ...];

const recursiveMap = (arr, cb) =>
  arr.map((obj, i, _arr) =>
    Array.isArray(obj)
      ? recursiveMap(obj, cb)
      : cb(obj, i, _arr)
  )

const termeknevRecursive = recursiveMap(input, ({ termeknev }) => termeknev);
console.log('\nThe Never-Ending Story (Arbitrary Depth):', termeknevRecursive);

Answer №2

In the dataset, the second and third elements are of type array rather than object.

Therefore, if you attempt to retrieve the value using data[1].termeknev, it will return null because there is no property termeknev in data[1]. Instead, you should access it as data[1][0].termeknev.

When iterating through the data array, make sure to verify in each iteration whether the element is of type array. If it is, you will need to iterate through that nested array to obtain the actual values.

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

Encountering a TypeError while trying to run Pythonshell on my Mac device

When I run a python script in node.js using python shell, it works perfectly on my Windows system. However, I encounter an error when trying to run the same thing on my Macbook: Error: TypeError: can't multiply sequence by non-int of type 'float ...

I am facing difficulty accessing the "All" drop-down menu on the Amazon.ca webpage using Selenium WebDriver in Java

Instructions: To begin, navigate to the Amazon home page Locate the "ALL" drop-down option at the top left corner of the page Attempt to click on this option using Selenium WebDriver with Java Sample Code Snippet: new WebDriverWait(driver, 20).until(Ex ...

No text appearing on iOS simulator when typing

I recently started learning React-Native and decided to follow a tutorial to create a login screen. I encountered an issue where the code in the tutorial was outdated. I am working on a login screen that consists of multiple components. However, one specif ...

How can I pass a value from JavaScript back to the .blade file in Laravel using DataTables?

I have some rows that are being displayed: https://i.sstatic.net/Y10X7.png The DataTable plugin within app.js is responsible for outputting each row. My goal is to target a specific value, ${row.category_id} let TABLE = $('#categoryList').Data ...

Issue with Refreshing onRowAdd in React Material Table

I am currently using Material Table to display my table data. However, when I use the onRowAdd function to add a new row, the page does not refresh properly. Instead, it reloads and gets stuck, requiring me to manually refresh again. newData => ...

Showing a pop-up on a click of a dynamically created table row, showcasing information specific to that row

I am facing a challenge with my dynamically generated table that is based on the JSON response from an AJAX call. What I am trying to achieve is to display additional data in a modal when a table row is clicked. This would be simple if the data was hard co ...

What is the best way to place a popover above a selected text section?

Imagine a situation where a body of text is present. When a word is highlighted within this text, a popover should appear with a tooltip positioned directly at the highlighted word. Think of it as similar to how a Mac displays definitions of words within ...

Is the validity of the expression !args.value || args.value.length true?

After analyzing this segment of code, I noticed an interesting expression: !args.value || args.value.length For instance, consider the following scenario: let v = {}; console.log(!v.value); //outputs true console.log(v.value); //outputs undefined con ...

Asking for a website link to utilize when sending a request in Node.js

I'm trying to create a user prompt for entering a URL and then making an HTTP request with the entered URL. However, I keep encountering an error that reads: "TypeError: Cannot read property 'parent' of undefined." Interestingly, when I har ...

Pass JS POST request data as body parameters

Is there a way to send a parameter as the post body to an API while also including the required Authorization header with the API key? How can I include a post body request with data set as "server_id: 12345"? What is the method to display the JSON res ...

What is the best way to programmatically close a bootstrap modal?

Currently, I am performing update operations through a modal. When the modal pops up, it loads specific row data that I intend to update. Here is the code for my modal: <form id="form1" runat="server"> <asp:ScriptManager ID="sm1" runat="serve ...

Utilizing jQuery to trigger events on nested elements

Here is the markup that I am working with: <ol> <li class="ListItem"> <span class="sub">@qItem.CategoryText</span> <input type="image" src="http://icons.iconarchive.com/icons/tatice/just-bins/256/bin-red-full ...

Searching through all objects in an array by specifying a field set in JavaScript

How can I efficiently search through an array of objects by specifying the fields to search within a function call and filtering out specific values? For example: const src = [ { id:1, name: "name1", age: 25}, { id: 2, name: "name2", age: 33} ] If I only ...

Converting an rrule date value from an array to a customized string format

Here is an array that I am working with: [{ evening_feeding: false evening_feeding_time: "19:00" feeding_frequency_rule: **"FREQ=DAILY;INTERVAL=2"** id: 890 morning_feeding: true morning_feeding_time: "04:00 ...

Filter a Vue table by column name with specific conditions

I am working on code that filters a table based on user input. The process involves selecting a column from a drop-down menu, choosing an operator from another drop-down menu, and entering a search value. I want to filter the table based on these criteria. ...

Having trouble updating button text with javascript

I am currently working in this fiddle at http://jsfiddle.net/vVsAn/4821/. I'm trying to create a button that changes text when clicked, but I have attempted several methods without success. Any assistance would be greatly appreciated. Below is my HTML ...

The Django project does not contain any JS script

Currently expanding my knowledge in Django and encountering an issue. The JS script is not being included in the Django project despite having the correct path. While the page itself with the graph block functions properly, the output of a round or bar cha ...

Sharing JSON data between components securely without displaying it in the URL through routing

Seeking to pass JSON through routing URL, my code in app.route.ts looks like this: {path: 'calculator', component: CalculatorComponent,data : {some_data : null}}, The code used to route the data is as follows: this.router.navigate(['/home ...

Clicking on an AJAX-retrieved element is not possible

Hey there! I'm currently working on creating an image gallery for the article editor in my project. Users can select any image that has already been uploaded or upload a new image, and then the image link will be placed into the editor. I am using the ...

Html.BeginForm does not offer onBegin or onComplete methods similar to Ajax.BeginForm

I am currently working with ASP.NET MVC 5 and have implemented a loader during form submission using Ajax.BeginForm: @using (Ajax.BeginForm("Filter", "Log", new AjaxOptions() { OnSuccess = "reloadGrid", OnFailure = "notifyError", HttpMethod = "POST", Load ...