What is the best way to store all the child elements of an object in an array?

I'm facing a challenge with the Google People API where I have a promise and need to convert parts of the data into an array. However, I am struggling to create child elements within the array.

let newArray = [];

for (var i = 0; i < obj.length; i++) {
    newArray.push(obj[i].requestedResourceName);
    for (var j = 0; j < obj[i].person.names.length; j++) {
        if (obj[i].person.names[j].metadata.source.type === 'CONTACT') {
            newArray[i].push(obj[i].person.names[j]);
        }
    }
}

The problem I'm encountering is: Error: Uncaught (in promise): TypeError: newArray[i].push is not a function

Answer №1

When you use

arr.push(this.k4kItems[a].requestedResourceName)
, you are inserting something that is not an array into arr[a].

A better approach would be to include an object with a children property.

let arr = new Array();

for (var a = 0; a < this.k4kItems.length; a++) {
  // Adding object with children array
  arr.push({item: this.k4kItems[a].requestedResourceName, children: []});
  for (var b = 0; b < this.k4kItems[a].person.names.length; b++) {
    if (this.k4kItems[a].person.names[b].metadata.source.type === "CONTACT") { 
      // Pushing to that array, notice we use .children to push child items
      arr[a].children.push(this.k4kItems[a].person.names[b]);
    }
  }
}

For a more modern and elegant alternative using map and filter, check out the following code:

const arr = this.k4kItems.map(item => ({
    item,
    children: item.person.names.filter(
       name => name.metadata.source.type === "CONTACT"
    )
}))

Answer №2

It is important to make sure that you are only pushing arrays into your arr array. If

this.k4kItems[a].requestedResourceName
is not an array, then you will encounter an error.

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 NbDatePicker does not display certain Spanish names

One issue I'm facing is with the Nb-DatePicker component in my project. I tried using {provide: LOCALE_ID, useValue: "es-MX"} in my app.component to display it in Spanish. However, when February, April, May, August, or December are selected, ...

Mistakes that occur while trying to expand a base class to implement CRUD functionality

Creating a base class in TypeScript for a node.js application to be extended by all entities/objects for CRUD operations is my current challenge. The base class implementation looks like this: export class Base { Model: any; constructor(modelName ...

I attempted to retrieve the id field of a jsonwebtoken following the user's login, but unfortunately, I was unable to access it

While working on the backend of my application, I encountered an issue trying to save the id field from a JSON Web Token (JWT) to an item that I created after a user logs in. Although I am able to log the JWT information successfully, I'm facing diffi ...

List of suggestions for autocomplete in Angular

My autocomplete function is set up like this: chooseArtist: OperatorFunction<string, readonly string[]> = (text$: Observable<string>) => text$.pipe( debounceTime(200), distinctUntilChanged(), map((term: any) => term. ...

Embedding a table row within an anchor element in Angular 4

Currently, I am facing an issue with a table that contains [routerLink] on each <tr>. This setup is preventing the "open link in a new tab" option from appearing when I right-click because there is no <a> tag. I attempted to enclose the table r ...

Tips for modifying a TypeScript object by its key value?

I am facing an issue where I have the key's value as a string and need to update the object based on this key value. Is there a method in TypeScript that can help me achieve this? I attempted to use the <object_name>[key] = value method but unf ...

Is it possible to assign 'lodash' separately in a hybrid AngularJS/Angular application with SystemJS?

I recently converted my hybrid AngularJS app to use TypeScript and SystemJS for module loading. However, I encountered an error in VS2015 related to Lodash: 'Cannot find name '_' Despite trying various solutions from Stack Overflow such as ...

Oops! It seems like you forgot to indicate a command before proceeding. Make sure to check out the available commands using '--help'

I keep encountering the following problem: Error: A command must be specified before proceeding. Use '--help' to see the available commands. whenever I try to use an ng command. ...

Issues arise during the deployment of Angular7 production build when passing through the Bitbucket package manager

I am working on a project to create a system that allows Angular components to be reused across multiple applications via BitBucket. Currently, I have the following setup: BitBucket Repo A - This repository stores the node module. The module is develope ...

What is the reason for not receiving a transpilation error when referencing a non-exported class?

As a relatively new learner of Typescript and Javascript (with a background in Java), I have been navigating the transition from a single large Typescript file containing multiple classes to utilizing multiple classes. While I have made progress with the i ...

Creating a Proxy for an Array in TypeScript: A Step-by-Step Guide

When attempting to utilize a Proxy for adding logic whenever a value in my array is set to a new value, I encountered an issue with TypeScript. The error arises from the fact that TypeScript does not support indexing an array with anything other than a num ...

Issues with Karma Testing: None of the Tests Executed Successfully

I am currently enrolled in the Angular Fundamentals course presented by Jim Cooper on Pluralsight. Despite following the course meticulously, using the same versions, and replicating the code exactly, I am facing an issue with running my Karma tests. Belo ...

angular ngSubmit not functioning as expected (button embedded within and module incorporated)

As a newcomer to angular, I am exploring the framework for the first time and diving into testing. Starting with a basic form: <form (ngSubmit)="onSubmit()"> <label for="test">Test Prompt: </label> <input typ ...

Utilizing Angular components within the paperbits framework

I've been attempting to integrate an Angular component into Paperbits either as a widget or as a component. According to the documentation, this should be possible at . However, I've been unable to successfully implement it and haven't come ...

Type property is necessary for all actions to be identified

My issue seems to be related to the error message "Actions must have a type property". It appears that the problem lies with my RegisterSuccess action, but after searching on SO, I discovered that it could be due to how I am invoking it. I've tried so ...

The 'searchText' property is missing an initializer and is not definitively assigned within the constructor

There is a variable declared in a class: public searchText: string; With strict mode enabled in TypeScript, the following error occurs: Property 'searchText' has no initializer and is not definitely assigned in the constructor Adding '&a ...

The debugger extension for Visual Studio Code in Chrome, [webkit-debug-adapter], received a response from the target application, but was unable to find any valid target

I am currently working on an Angular/TypeScript application and have been able to debug the TypeScript code in Chrome thanks to the map files. Recently, I decided to install the Debugger for Chrome extension from Visual Studio Marketplace. You can find it ...

Tips for showcasing a collection of interactive buttons (with each column as a button) utilizing mat-table within Angular 8

I am dealing with a situation where I need to implement dynamic buttons on a page using Angular 8. Furthermore, the buttons will change dynamically based on the selection made in a drop-down menu. ...

Typescript enables bidirectional control of Swiper

I attempted to use the two-way control slider example from Swiper documentation, but I encountered TypeScript errors that prevented it from working correctly. Is there a way to make it compatible with TypeScript? The specific errors I received were: TS23 ...

Having issues with the ASP.NET Web Api and Angular Frontend integration

I recently tried following a guide on ASP.NET Web Api and Angular, which you can find here. While I followed the steps closely, the only difference was that I used .NET version 7 instead of version 6 for the Web Api. When I ran the project for the first ti ...