What is the process for retrieving every individual object within a nesting object that spans four levels deep?

I am working on creating an Object that consists of 3 other Objects, with one of them containing three additional Objects. My goal is to set a value for each of these Objects.

However, I am unsure about the types of Objects present as they all seem to be Object types.

I attempted to traverse through the Objects, first recognizing whether it is an Object or Array, then traversing twice and ultimately trying to set the values. Unfortunately, this led to an error being displayed in the console.


>Cannot set property 'www.google.com' of undefined
TypeError: Cannot set property 'www.google.com ' of undefined
at eval (userscript.html?name=
at Array.forEach ()

The original script involves excluding the four levels of nested Objects. Check out the code for the browser search tool here

    Object.keys(iconsData).forEach(function(value1) {

        if(iconsData[value1].constructor === Array){
            iconsData[value1].forEach(function (value2) {
                console.log('typeArray--'+iconsData[value1].constructor)
                value2.host.forEach(function(host) {
                    iconsData.hostCustomMap[host] = value2.custom     // The console shows an Error maybe here
                })
            })
        } else if (iconsData[value1].constructor === Object) {
            Object.keys(iconsData[value1]).forEach(function (value2) {
                console.log('typeObject--'+iconsData[value1].constructor)
                iconsData[value1][value2].forEach(function (value3) {
                    value3.host.forEach(function(host){
                        iconsData.hostCustomMap[host] = value3.custom
                    });
                });
            });
        }
    })

The below code contains nesting Objects within the structure.

(function () {
    'use strict';
    var keyword = {
        beforePopup: function (popup) {
            var text = window.getSelection().toString().trim();
            GM_setValue('search', text);
            popup(text);
        },
        beforeCustom: function (custom) {
            var text = GM_getValue('search');
            GM_setValue('search', '');
            custom(text);
        },

    };

var iconsData = {
    iconArraya: {
        Arraya: [
            {
                name: 'Google',
                image:'https://i.ibb.co/R9HMTyR/1-5.png',
                host: ['www.google.com'],
                popup: function (text) {
                open('https://search.google.com/live?keyword=' + encodeURIComponent(text));
                }
            }
        ],
        Arrayb: [
            {
                name: 'Bing',
                image: 'https://i.ibb.co/pwkLTFc/1.png',
                host: ['www.bing.com'],
                popup: function (text) {
                open('https://www.bing.com/live?keyword=' + encodeURIComponent(text)');
                }
            }
        ],
        Arrayc: [
            {
                name: 'Youtube',
                image:'https://i.ibb.co/FWVJ3Kf/1-2.png',
                host: ['www.youtube.com'],
                popup: function (text) {
                open('https://www.youtube.com/live?keyword=' + encodeURIComponent(text)');
                }
            }
        ]
    },
    iconArrayb: [
        {
            name: 'open',
            image:'https://i.ibb.co/fxpm6Wc/image.png',
            host: [''],
            popup: function (text) {
                open(encodeURIComponent(text));
            }
        }
    ],
    iconArrayc: [
        {
            name: 'copy',
            image:'https://i.ibb.co/PQ5xM2R/2-1.png',
            host: [''],
            popup: function (text) {
                document.execCommand('copy', false, null))
            }
        }
    ],
    hostCustomMap: {}
    }


Answer №1

An error occurred when trying to assign 'www.google.com' to an undefined property

This issue arises because the property hostCustomMap does not exist in iconsData.

To resolve this, make sure to include hostCustomMap as a property within the iconsData object, as shown in the original code snippet.

Modify your code like this:

var iconsData = {
    iconArraya: ...,
    iconArrayb: ...,
    iconArrayc: ...,
    iconArrayD: ...,
    hostCustomMap: {}
}

Avoid this incorrect approach:

var iconsData = {
    iconArraya: ...,
    iconArrayb: ...,
    iconArrayc: ...,
    iconArrayD: ...
}

var hostCustomMap = {}

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 onChange event for React select is being triggered twice, incorrectly using the old value the second time

I am currently implementing React Select to display a list of items. When an item is changed, I need to show a warning based on a specific flag. If the flag is true, a dialog box will be shown and upon confirmation, the change should be allowed. After each ...

How can one change the color of movable tiles to red while keeping the rest of the tiles in their original state in a puzzle game?

In this section of our code, the function moveTile is responsible for moving a tile. How can I modify it so that the hover color changes to red? function moveTile(identity) { var emptyId = findEmptySpace(); if (isEmptyNeighbor(identity)) { document.ge ...

What are the steps to generate a multiline chart using d3.js with json data specifically formatted for nvd3?

I attempted to create a multi-line chart using nvd3, but encountered roadblocks when trying to make significant modifications. I am considering building my own chart using d3js directly, but I'm finding it challenging to grasp the concept of 'thi ...

What is the process of transferring an object to a different scope by utilizing checkboxes and Ajax?

I find myself lost in contemplation. I have a checkbox that I want to utilize to move a corresponding object to another area on my page. Furthermore, I am interested in transferring only one specific field of this checked object. In the past, I utilized Aj ...

Issue with array_rand in PHP not producing desired results

Delving into the world of PHP during my training, I stumbled upon the array_rand function that generates random indexes. It allows you to specify how many random indexes you want returned. However, what happens when this number matches the actual length of ...

Suggestions on transitioning from jQuery version 1.2.6 to YUI 3?

I am currently working on a web application that utilizes both jQuery 1.2.6 and YUI 2.6.0, but I am considering upgrading one or both of these libraries. The most recent versions available at the time are jQuery 1.3.2 and YUI 3.0.0 (beta 1). Initially, we ...

Can you explain the {| ... |} syntax in JavaScript to me?

While reviewing a javascript codebase, I stumbled upon a section of code that appears as follows: export type RouteReducerProps = {| error?: Error, isResolving: boolean, isResolved: boolean, hasFailed: boolean, |}; Upon closer inspection, it seem ...

Customizing style with state using react and styled-components

As a newcomer to react and styled-components, I find myself in a bit of a mess due to my lack of understanding of how it all functions. Let's start from the beginning. I have a basic page (App.js) that displays two components called "Knobs". Each &ap ...

Converting integers to strings is not possible, just as converting strings to two-dimensional integer arrays is not

I find myself once again trying to solve the puzzle of error messages that keep appearing. Currently, I am delving into working with arrays - both regular and multi-dimensional. However, I am encountering difficulties in two areas: a) populating the arra ...

Why isn't the function in my React child component passing its parameters to the parent component's function as expected?

In the parent: const [currentPinPosition, setCurrentPinPosition] = React.useState({ lat: 0 , lng: 0 }); const updateCurrentPinPos = (position) => { console.log(position); setCurrentPinPosition({ lat: position.lat, lng: position.lng }); }; / ...

The most effective way to export ThreeJS models to Blender

I found a bedroom object on Blender that I downloaded from this source. When exporting it in json format to load it into Three.js, I noticed that only one mesh of the bed component was included instead of all the meshes I had selected. All components of ...

Exploring the PHP array slice feature

Hey there, I'm currently facing a challenge with iterating through my array chunks. I am working on creating an image gallery where groups of three images follow a specific pattern and then the next set of three follows the opposite pattern. I believ ...

Switch videos within the video tag as you scroll

I am trying to implement a video tag within a div element on my website. Here is the current code: <div class="phone" align="center"> <div class="phone-inner"> <video width="100%" height="100%" autoplay="" loop="" muted id="phonevideo ...

What happens when you use pointer arithmetic to access one element beyond the end of an array and then dereference the pointer?

When I dereference an array and add 5, which exceeds the elements available within the array, the value that is printed is 32767. This output, which I see in my IDE, seems puzzling to me. #include <stdio.h> int main(void) { int i; int meat ...

Encountering npm install failure post updating node version

When attempting to execute npm i, the following error message is now appearing: npm i npm ERR! path /home/ole/.npm/_cacache/index-v5/37/b4 npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall mkdir npm ERR! Error: EACCES: permi ...

When trying to make a POST request, the browser displayed an error message stating "net::ERR_CONNECTION

Currently, my project involves coding with React.js on the client side and Express.js on the server side. I have encountered an issue when attempting to use the POST method to transmit data from the client to the server for storage in a JSON file. The erro ...

Steps for sending an array from PHP to an AJAX response in JavaScript

How can I send an array from PHP to an AJAX call? AJAX call: $.post('get.php', function(data) { alert(data); }); get.php $arr_variable = array('033', '23454'); echo json_encode($arr_variable); When the data is alert ...

Acquire JSON data from a URL and display it on the webpage

I'm facing an issue where the JSON data I'm trying to fetch from a URL is not displaying due to an uncaught reference error in my code. How can I modify the code to ensure that the data gets shown? var url = "https://fantasy.premierleague.com/ ...

Objective-C's implementation of arrays in the style of C, Java, and other programming

Although Apple prefers using NS objects instead of primitive types, I require the functionality of an array for direct access to items at specific indices. It's challenging to find tutorials or resources on how to use basic primitive arrays due to thi ...

Having trouble updating the state value using useState in React with Material-UI

I have developed a unique custom dialog component using Material-UI const CustomDialog = (props) => { const [dialogOpenState, setOpen] = React.useState(props.dilaogOpenProp); return ( <> <CssBaseline /> <Dialog ...