The operation to assign a value to property 'two' cannot be completed as it is currently undefined

I'm facing an issue with the code below and cannot figure out why I am encountering the error message. I have ensured that each object contains a value, so why is there a reference to 'undefined'?

Cannot set property 'two' of undefined

interface FakeObj {
  one: string | null;
  two: string | null;
  three: string | null;
}

const objectOne: FakeObj[] = [
   {
     one: null,
     two: "Two",
     three: null
   }
];

const objectTwo: FakeObj[] = [
   {
     one: "One",
     two: null,
     three: "Three"
   }
];

const newObject = objectOne.map((search, index) => {
  return Object.entries(search).reduce((acc, [key, value]) => {
    acc[key] = !value && objectTwo.length > index ? objectTwo[index][key] : value;
  }), {};
});

console.log(newObject);

UPDATED: After updating the code, I encountered new issues:

Cannot set property 'two' of undefined

Cannot create property 'two' on string 'One'

Answer №1

To start, it is important to define the objects as an array:

const objectOne: FakeObj[] = [
  {
    one: null,
    two: "Two",
    three: null
  }
];

Make sure to use const objectOne: FakeObj[] instead of just const objectOne: FakeObj.

Regarding the issue with undefined, ensure that you are returning a value from the reduce function so that acc is not undefined on subsequent calls.

Similarly, remember to return inside your map function to prevent the final log from displaying just [undefined].

Consider using this revised code snippet (although it may require further understanding of your objective):

const newObject = objectOne.map((search, index) => {
  return Object.entries(search).reduce((acc, [key, value]) => {
    acc[key] = !value && objectTwo.length > index ? objectTwo[index][key] : value;

    return acc;
  },{})
});

console.log(newObject);

Response for additional query in the comments:

const newObject = objectOne.map((search, index) => {
  return Object.entries(search).reduce((acc: FruitObj, [key, value]) => {
    acc[key as keyof FruitObj] = !value && objectTwo.length > index ? objectTwo[index][key as keyof FruitObj] : value;

    return acc;
  },{one: null, two: null, three: null})
});

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

Encountered a runtime error in NgRx 7.4.0: "Uncaught TypeError: ctor is not a

I'm facing difficulties trying to figure out why I can't register my effects with NgRx version 7.4.0. Despite simplifying my effects class in search of a solution, I keep encountering the following error: main.79a79285b0ad5f8b4e8a.js:33529 Uncau ...

Loading texts with the same color code via ajax will reveal there are differences among them

I am currently designing a webshop with green as the primary color scheme. Everything is functioning perfectly, but I have noticed that the text within an ajax loaded div appears brighter than it should be. The text that loads traditionally is noticeably d ...

Displaying various Ajax html responses

The function $('.my-button').click(function(e) is designed to display the output of the MySQL query in display.php, presented in HTML format. While it functions correctly, since each button is looped for every post, the script only works for the ...

What is the process for retrieving the value of a text box using V-Model?

Link to the code snippet <td><input class="input" v-model="user.name" /></td> After accessing the provided link, I noticed a unique input textbox. Is there a way to extract specific text values like a,b,c from this te ...

AngularJS $routeProvider is experiencing difficulties with its routing functionality

I am a beginner with Angular and I'm trying to understand how multiple routes can lead to the same view/templateUrl and controller. This is what I have written: angular .module('mwsApp', [ 'ngAnimate', 'ngCookies&ap ...

Leverage the https module within your React Native application

How can I integrate the https standard library module from Node.js into a React Native project? Specifically, I need to use https.Agent for axios. Is there a recommended approach for achieving this integration? ...

Why does the combination of "minus, space, minus" result in the "plus" operation?

When running the command 'node -e 'console.log(- -1)' it outputs 1, which is expected. However: When executing the command 'node -e 'console.log(1 - - 1)' it displays 2, which puzzles me. It seems like when subtracting a ne ...

The function crypto.randomUUID() does not exist in the Vitest library

vite.config.ts import { sveltekit } from '@sveltejs/kit/vite'; const config = { plugins: [sveltekit()], test: { include: ['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], environment: 'jsdom', glo ...

React has reached the maximum update depth limit

In my current project, I am developing a react application that involves a user inputting a search term and receiving an array of JSON data from the backend. On the results page, I have been working on implementing faceted search, which includes several fi ...

Having trouble adding items to an array within a Javascript promise

I am facing an issue with the exported function in a Nextjs app, which acts as an API page. The problem arises when the 'domainnames' array returns nothing in the 200 response. Interestingly, if I exclude the 'GetDomainStatus()' funct ...

Retrieve the jQuery widget instance by selecting an element within the widget

I am currently developing a widget using the Jquery widget factory. The abbreviated version of the code looks something like this: _create: function(){ this.element.hide(); //hides original input element this.newInput=$("<input>"); //creates ...

The Jquery code encountered an issue where it was unable to access the property 'length' of an undefined

My goal is to submit a form using jQuery and AJAX, which includes file upload functionality. The challenge I'm facing is that the forms are dynamically created, so I need to identify which form was clicked and retrieve its input values. $(document).r ...

The last javascript file that was included has been overlooked

When using jqplot, I noticed that the last included plugin is being ignored. If I switch their positions, the first to last one works while the last one does not. There are no errors in the console to indicate what might be going wrong. Moving the canvasOv ...

Is it possible to set all UI forms to a readonly/disable mode?

We have a specific requirement where, if the user's access level is set to "READ ONLY", all form input elements should be made readonly. Our coding approach involves using a template HTML that contains widgets which are referenced in the correspondin ...

Having a parameter that contains the characters '&' and '&' can potentially disrupt an AJAX call

Even though there is a similar question here: Parameter with '&' breaking $.ajax request, the solutions provided do not apply to my specific issue. This is because both the question and answers involve jQuery, which I am not familiar with. I ...

Identifying Typescript argument types

The given code is functional, but I am looking to refactor it for better clarity using Typescript syntax if possible. class Actions { actions: string[] } type Argument = object | Actions; export class GetFilesContext implements IExecutable { execute( ...

"Encountering a problem with compression in Kafka while using the Node.js client with

I am currently utilizing the kafka-node library to consume data from Kafka. It appears that the data I am receiving is compressed with SNAPPY. How can I decompress this data once it has been retrieved? I attempted to use the node-snappy library for decompr ...

How can we add a class to a radio button using jQuery when it is checked, and remove the class when it

I'm looking for help with using jQuery to toggle between two radio buttons and display different divs based on the selection. jQuery(document).ready(function($) { if ($('#user_personal').is(':checked')) { $('.user_co ...

The div element fails to display even after invoking a JavaScript function to make it visible

As a newcomer to JavaScript & jQuery, please bear with me as I ask a very basic question: I have created the following div that I want to display when a specific JavaScript function is called: <div id='faix' class="bg4 w460 h430 tac poa ...

Is there a way to automatically hide divs with the style "visibility:hidden" if they are not visible within the viewport?

Currently, I am working on developing a mobile web app. Unfortunately, Safari in iOS 5.1 or earlier has limited memory capabilities. In order to reduce memory usage while using css3 transitions, I have discovered that utilizing the css styles "display:none ...