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

Tips for transmitting variable values through a series of objects in a collection: [{data: }]

How to pass variable values in series: [{data: }] In the code snippet below, I have the value 2,10,2,2 stored in the variable ftes. I need to pass this variable into series:[{data: }], but it doesn't seem to affect the chart. Can anyone guide me on ...

Error: Unexpected top-level property "import/order" in ESLINT configuration

I'm in the process of setting up a guideline to include one blank line between internal and external imports. .eslintrc.json: { "parser": "@typescript-eslint/parser", "env": { "es6": true, " ...

retrieve a nested object's property using a dynamic string

Here is the object model I am working with: export class FrcCapacity { constructor( public id?: number, public frcId?: number, public capGroupId?: number, public capGroup?: CapGroup, public salesProductId?: number, public p1?: num ...

Getting just the main nodes from Firebase using Angularfire

I'm having trouble figuring out how to print just the parent element names from the structure of my database. The image provided shows the layout, but I can't seem to isolate the parent elements successfully. ...

Tips for consolidating all functions into a single file for ReactJS inheritance:

I'm curious about something. In Angular JS, we have the ability to create a global service file that can be inherited by every component. This allows us to use the functions written in the global service file within each respective component. Is ther ...

Ensuring the accuracy of user input

Can someone assist me with comparing two dates in JSP? I need validation that alerts the user when a future date is entered. The start date or end date should not be in the future. The date format is 12-5-2011 10:51:49. Any help would be greatly apprecia ...

Experiencing difficulty accessing the response header in Angular 16 due to CORS restrictions

When attempting to retrieve the response header from my post call, I am encountering difficulties as it appears there are "no headers" or I may be doing something incorrectly. On the backend, I am utilizing ASP.NET Core. Below is a basic outline of my API ...

Bandcamp API sales data retrieval feature

Looking for assistance with a call to the Bandcamp API. Every time I request /http://bandcamp.com/api/sales/1/sales_report/, I receive this message in the response: /"error_message":"JSON parse error: 757: unexpected token at ''/ ...

Error: Cannot access the length property of an undefined value in the JEST test

I'm currently working on incorporating jest tests into my project, but I encountered an error when running the test. The issue seems to be related to a missing length method in the code that I am attempting to test. It appears to be originating from s ...

Tinymce editor does not display icons as expected

I am attempting to create a custom styled list that is editable with tinymce. The list-items are using Material-Check-Icons as bullet-points, which are added as css-pseudo-elements ::before. This setup works well, but when I integrate tinymce (v5) into the ...

Root scope digest trigger delay

When invoking $scope.$apply() ten times consecutively, it is expected that ten root scope digests will occur. If the call to $scope.$apply() is debounced so that the trailing call always completes, can we assume that the final state of the application rem ...

Concealing URL parameters in ui-sref (using ui.router)

Here is the HTML code I am working with: <a ui-sref="videoParent.Display.video({videoName:'[[sVid.slug]]', videoId:'[[sVid.videoID]]'})"><p>[[sVid.name]]</p></a> The parameters videoName and videoId are retriev ...

Can a unique intrinsic type be created from scratch?

Ever since template literals were introduced in Typescript (PR), we've had access to various useful functions in our types: Uppercase Lowercase Capitalize Uncapitalize For more information, refer to the official documentation. Although it may seem ...

Transforming a PHP cURL call to node.js

Currently exploring the possibility of utilizing the Smmry API, however, it seems that they only provide PHP API connection examples. Is there anyone who could assist me in adapting it into a JS request? My requirement is simple - I just need it to analyz ...

Tips on manually refreshing AngularJS view using ControllerAs syntax?

As I work on creating a user-friendly dashboard with widgets that can be sorted, docked, and floated, I encountered an issue. The controls I am using generate floating widgets as HTML at the bottom of the DOM, outside the controller scope where they were c ...

Numerous navigable tabs all on a single page

After following a tutorial on YouTube to create scrollable tabs, I successfully implemented it using Bootstrap 5. However, I'm facing challenges in getting multiple scrollable tabs to function on a single page. Although the tabs and tab-content are fu ...

How can an external style sheet be inserted into an iframe?

My website features an editor on one side and an iframe on the other. Currently, anytime HTML code is entered into the editor and a keyup event occurs, the iframe updates automatically. I am looking to add default styling to the code entered in the editor ...

Ways to address the issue of "$ is not a function"

Whenever I attempt to upload an image, this error message pops up: $ is not a function The source of the error can be found here: $(document).height(); ...

Applying a Typescript Generic to enhance the functionality of the API fetcher

I've written a simple function to enhance fetch functionality. I am currently exploring how TypeScript Generics can be utilized to define the Type for 'data' in the return. const apiFetchData = async ( url: string, options = {}, ): P ...

Node unable to interpret accented characters from CSV file input

Currently, I am utilizing npm fast-csv as my CSV reader/writer tool. It offers a simple and straightforward way to handle CSV files. My goal is to use this tool along with iconv to deal with "accented" characters and non-ASCII characters by converting them ...