Greg Harner
Greg Harner

Reputation: 145

How do you push child elements of an object into an array?

I have a promise from a Google People API, and I want to create an array from portions of the data. I cannot figure out how to make child elements in the array.

let arr = new Array();

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

The error is: Error: Uncaught (in promise): TypeError: arr[a].push is not a function

Upvotes: 1

Views: 1094

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92274

You are adding something that is not an array to arr[a] when you do arr.push(this.k4kItems[a].requestedResourceName).

One suggestion would be to add an object containing 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]);
    }
  }
}

Here's a more modern and elegant way of doing the same thing using map and filter

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

Upvotes: 3

SeleM
SeleM

Reputation: 9638

You have to ensure that you push arrays in your arr array, means if this.k4kItems[a].requestedResourceName is not an array, you'll have that error.

Upvotes: 0

Related Questions