When attempting to access an object within an array in JavaScript, an error is thrown stating: "TypeError: Cannot read property 'data' of undefined."

I am facing an issue while trying to access and manipulate an object within an array of objects using JavaScript in Google Apps Script. The error message I receive is: "TypeError: Cannot read property '0' of undefined"

The JSON data (obtained from an API response) is stored in the variable named "data" and looks like this:

[{
    "values": {
        "article_number": [
            {
                "locale": null,
                "scope": null,
                "data": "000000000010137290"
            }
        ],
        "article_description": [
            {
                "locale": null,
                "scope": null,
                "data": "SDS Mini Desktop Organiser 3 Draw Sil"
            }
        ],
        "marketing_description": [
            {
                "locale": "en_US",
                "scope": null,
                "data": "SDS Mini Desktop Organiser and 3 Drawers Mesh Silver"
            }
        ]
    }
}]

My goal is to extract the "data" element within each object and store them in a new object. Here is my current approach:

var products = [];
data.forEach(function(elem, i) {
    products.push({
        article_number: elem["article_number"][0]["data"],
        article_description: elem["article_description"][0]["data"],
        marketing_description: elem["marketing_description"][0]["data"]
    });
});

I would greatly appreciate any help or guidance on how to resolve this issue. I have attempted removing the [0] index, but that only results in another error: "TypeError: Cannot read property 'data' of undefined". I am puzzled as I believed accessing index 0 of the array should work.

Answer №1

This explanation may be a bit more detailed than what you were expecting, but here is the breakdown of the process I followed.

  1. Loop through the keys of the object.
  2. Locate the data property within the corresponding object.
  3. Construct a new object with pairs in the form of key: data.

Output:

[
  {
    "article_number": "000000000010137290",
    "article_description": "SDS Mini Desktop Organiser 3 Draw Sil",
    "marketing_description": "SDS Mini Desktop Organiser and 3 Drawers Mesh Silver"
  }
]

Complete code snippet:

let receivedData = [{
  values: {
    article_number: [{
      locale: null,
      scope: null,
      data: "000000000010137290",
    }, ],
    article_description: [{
      locale: null,
      scope: null,
      data: "SDS Mini Desktop Organiser 3 Draw Sil",
    }, ],
    marketing_description: [{
      locale: "en_US",
      scope: null,
      data: "SDS Mini Desktop Organiser and 3 Drawers Mesh Silver",
    }, ],
  },
}, ];

let allItems = [];

for (let j = 0; j < receivedData.length; j++) {

  let newObject = Object.keys(receivedData[j].values).reduce((accumulator, current) => {
    accumulator[current] = receivedData[j].values[current][0].data;
    return accumulator;
  }, {});

  allItems.push(newObject);
}

console.log(allItems);

Answer №2

let data1 = [{
    "values": {
        "article_number": [
            {
                "locale": null,
                "scope": null,
                "data": "000000000010137290"
            }
        ],
        "article_description": [
            {
                "locale": null,
                "scope": null,
                "data": "SDS Mini Desktop Organiser 3 Draw Sil"
            }
        ],
        "marketing_description": [
            {
                "locale": "en_US",
                "scope": null,
                "data": "SDS Mini Desktop Organiser and 3 Drawers Mesh Silver"
            }
        ]
    }
}]
var product = []; 
data1.forEach(function (elem, i) { 
product.push({ 
article_number: elem.values["article_number"][0]["data"], 
article_description: elem.values['article_description'][0].data, 
marketing_description: elem.values['marketing_description'][0].data });
}); 
console.log(product)

let data1 = [{
    "values": {
        "article_number": [
            {
                "locale": null,
                "scope": null,
                "data": "000000000010137290"
            }
        ],
        "article_description": [
            {
                "locale": null,
                "scope": null,
                "data": "SDS Mini Desktop Organiser 3 Draw Sil"
            }
        ],
        "marketing_description": [
            {
                "locale": "en_US",
                "scope": null,
                "data": "SDS Mini Desktop Organiser and 3 Drawers Mesh Silver"
            }
        ]
    }
}]
var product = [];
data1.forEach(function (elem, i) {
    product.push({ article_number: elem.values.article_number[0].data, article_description: elem.values.article_description[0].data, marketing_description: elem.values.marketing_description[0].data });
});
console.log(product)

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

document.addEventListener versus $().on

Recently, I came across an odd behavior while trying to add event listeners to the document. Strangely, when adding listeners to HTMLElements, everything worked smoothly, but for some reason, adding a listener to the document did not have any effect. Howev ...

Parsing of CSS and Javascript is disabled within iframes

Within my node.js application, I have configured an endpoint where I can load some parsed HTML code. This is achieved through the following code: app.get('/code', function (req, res) { res.setHeader('Content-Type', 'text/html& ...

Sending data from Ruby to JavaScript

I'm currently implementing an SMS validation feature on a Sinatra website. Here is the code snippet that I am using: post '/coop/sendcode' do @code = Random.rand(1000..9999).to_s phone = params[:phone].to_s HTTParty.get('http:// ...

Determine the text's length inside a div element by utilizing the div itself

I have a div with a fixed width of 30% and I am trying to find the length of the text within that div. Check out my JSFiddle for the code. The current code snippet I am using is: var text=$('#test').text(); text=text.trim(); var len=text.lengt ...

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...

What is the best way to interpret a nested JSON object?

Recently I've crafted an object that looks like this. myObj = { "name":"John", "age":30, "cars": [ "car1":"Ford", "car2":"BMW", "car3":"Fiat" ] } While it's pretty straightforward to read the name and age properties, I find ...

The authentication status of req.isAuthenticated for Passport is consistently marked as untrue

I am having issues with my authentication system. Let's start by looking at my node.js file: //Initializing Express Web Server var express = require('express'); var app = express(); var http = require("http").Server(app); var lusca = requi ...

What is the process for adding a naked domain (without www) on GoDaddy that is deployed through Heroku?

I have successfully deployed a domain through Heroku, and it is functioning properly with the www prefix. However, when attempting to access the domain without the www, it fails to render correctly. I have tried adding both versions of the domain (with www ...

My website has a navbar button that is not directing to the intended section of the screen

I have created this HTML code for my Navbar buttons: <button class="navbar-toggle" data-toggle = "collapse" data-target=".navHeaderCollapse"> <span class="icon-bar"></span> <span class="icon-bar">< ...

Error message in vuejs: JSON parsing error detected due to an unexpected "<" symbol at the beginning

I have been trying to troubleshoot this issue, but I am having trouble understanding how to resolve it. Currently, I am using lottie-web in a project and need to set the animation parameters on an object in order to pass them as a parameter later. This i ...

Addressing component validation conflicts in Vuelidate on VUE 3

I am currently experiencing an issue with VUE 3 Vuelidate. In my project, I have 2 components that each use Vuelidate for validation (specifically a list with CRUD functionality implemented using modals). However, when I navigate from one component to anot ...

Troubles faced while performing a table update in PHP and MySQL

I need help updating a MySQL table using PHP. Some rows in the table have duplicate index values under the column 'num'. I have an array of numbers that I want to update into a column named 'code'. Click here for an illustration of t ...

streaming an HTML5 video directly from memory source

After retrieving multiple encrypted data using ajax queries and performing necessary manipulations to turn them into a valid video, I find myself at a standstill. The binary of the video is now stored in memory, but I am unsure how to display it. To confi ...

Provide input to npm when running "my command" and utilize that input within my functions

Consider the contents of app.js const { doCoolStuff } = require("./api/myApi"); // grab parameter from command line and store it in "myParam" doCoolStuff(myParam); ... // more code And Package.json: { "name": "------ ...

My custom PHP page designed to insert new records into a MySQL database table appears to be ineffective as it is not updating the table as intended

Firstly, I have confirmed that the const.php file is located in the same directory as the page. I am in the process of developing a web page that enables administrators to add multiple entries to a MySQL table through the website. The functionality involv ...

Is there a way to toggle the visibility of a textarea with a button using knockout and the foreach binding?

Knockout is new to me and I have encountered an issue. I am trying to create a button and textarea for each project, with the textarea initially hidden on page load. When the button is clicked, it should toggle the visibility of the corresponding textarea. ...

Executing background operations in Meteor.js

Let me lay out my situation: 1. Extracting data from example.com at regular intervals 2. Storing it in a Mongodb database 3. Subscribing to this data in a Meteor App. Since I'm still learning Meteor, here's my plan: 1. Develop a scraper script ...

Guide to crafting a custom asynchronous function in a separate file using Express JS

I have a specific function that I want to create called: my_function.js: module.exports = function(req, res, next){ var js_obj; // Do something with the JavaScript object above // Afterwards, I want to append "js_object" to the request object: req.js ...

Preserve the current slide in JavaScript even after the page is refreshed

I have implemented a JavaScript slide that contains a gridview. My goal is to maintain the current slide even after a postback or page refresh, as each gridview serves a different function. Here is an excerpt of my code: Html: <div class = "callbacks ...

Guide to implementing bidirectional data binding for a particular element within a dynamic array with an automatically determined index

Imagine having a JavaScript dynamic array retrieved from a database: customers = [{'id':1, 'name':'John'},{'id':2, 'name':'Tim}, ...] Accompanied by input fields: <input type='text' na ...