Create a new array containing the keys from an array of objects

My task involves extracting the key puppies from an array of objects and returning it in a new array: The input is an array of dogs structured like this:

[
  {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof'] },
  {breed: 'Rottweiler', puppies: ['Biscuits', 'Mary'] }
]

The goal is to create an array containing all the puppies from all the dogs:

['Fluffy', 'Doggo', 'Floof', 'Biscuits', 'Mary']

This is the code I have written so far:

function collectPuppies (dogs) {

    let solution=[];
    for(let i=0; i<dogs.length; i++){
      solution.push(dogs[i].puppies);
    }
    return solution;
  }

Although it adds the names to the solution, they are returned within double brackets [[ ]]:

Expected [ [ 'Spot', 'Spotless' ] ] to deeply equal [ 'Spot', 'Spotless' ]

I came across a similar solution in this thread, indicating that I may be on the right track but struggling to pinpoint my mistake. Any assistance would be greatly appreciated. Thank you.

Answer №1

Learn how to use the spread syntax to add items to an array:

const dogs = [{"breed":"Labrador","puppies":["Fluffy","Doggo","Floof"]},{"breed":"Rottweiler","puppies":["Biscuits","Mary"]}];
  
function gatherAllPuppies(dogs) {
  const result = [];
  
  for (let i = 0; i < dogs.length; i++) {
    result.push(...dogs[i].puppies);
  }
  
  return result;
}

console.log(gatherAllPuppies(dogs));

Alternatively, you can retrieve the puppies using Array.map() and flatten the output by spreading it into Array.concat():

const dogs = [{"breed":"Labrador","puppies":["Fluffy","Doggo","Floof"]},{"breed":"Rottweiler","puppies":["Biscuits","Mary"]}];
  
const gatherAllPuppies = (dogs) => [].concat(...dogs.map(({ puppies }) => puppies));

console.log(gatherAllPuppies(dogs));

Answer №2

Within the array of objects, there is a sub-array called puppies which needs to be handled differently. Rather than simply adding this sub-array to the main solution array, each individual puppy within the puppies array should be added separately. This can be achieved by looping through the puppies array using forEach() method. Here's an example:

dogs[i].puppies.forEach((puppy) => {solution.push(puppy)});

The revised function:

function collectPuppies (dogs) {
    let solution=[];
    for(let i=0; i<dogs.length; i++){
       dogs[i].puppies.forEach((puppy) => {solution.push(puppy)});
    }
    return solution;
}

Answer №3

You could combine.

const cats = [ {breed: 'Siamese', kittens: ['Whiskers', 'Fluffy', 'Stripey'] }, {breed: 'Persian', kittens: ['Mittens', 'Tabby'] } ]

const gatherKittens = cats =>
    cats.map(c => c.kittens).reduce((a,b) => a.concat(b), []);
  
console.log(gatherKittens(cats));

Answer №4

To achieve this, all you need is the reduce method of Array.prototype.

x=[ {breed: 'Husky', puppies: ['Bear', 'Snowball', 'Ghost'] }, {breed: 'Golden Retriever', puppies: ['Max', 'Buddy'] } ] ;

var result=x.reduce((y,e)=>y.concat(e.puppies),[]);

console.log(result);

Answer №5

Array.prototype.push will add all arguments to the array, but not the individual elements of each argument.

An easy fix for your code is to swap out push with concat:

The concat() function combines two or more arrays together.

function gatherKittens(cats) {
   let result = [];
   for (let j=0; j < cats.length; j++){
       result = result.concat(cats[j].kittens);
   }
   return result;
}

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

Angular's change detection mechanism triggers too frequently

I'm dealing with a situation in one of my controllers where I have the following code: @HostListener('window:resize') onResize() { this.currentWindowWidth = window.innerWidth; } This code determines different views to render based on the ...

How to Retrieve an Image from a Server Using Node.js and Express

I have successfully implemented a feature to upload images to my server and then store them in the Postgresql database. However, I am facing an issue when trying to display an image on the browser by entering the URL like "http://localhost:5000/photoURL/ ...

"Error TS2339: The property specified does not exist within type definition", located on the input field

When a user clicks a specific button, I need an input field to be focused with its text value selected entirely to allow users to replace the entire value while typing. This is the markup for the input field: <input type="text" id="descriptionField" c ...

Utilizing Next.js to conditionally display data

My current challenge involves rendering data fetched from an API. The data is in JSON format, and I have a conditional logic to push a specific element based on the fetch result. {status: 'success'} If the fetch fails, I need to handle it by pus ...

What is the best way to link a newly created contact to the current user in Mongoose?

I'm faced with the challenge of creating a contact that is specifically added to the current user's contact array. Currently, my controller only creates a generic contact and doesn't cater to the individual user. Controller: function cont ...

What is the best method for passing a JavaScript object to PHP using Ajax?

I have looked into similar questions like this and this, but none of them have helped me solve my issue. When I check the console log for my data, it displays the following: Object["row_LM#00000010", "row_LM#00000002", "row_LM#00000009", "row_LM#00000008" ...

Retrieve the Axios response without interruption, even in the event of an exception, when making API calls with multiple files

Currently, as a beginner diving into Vue.js, I am exploring the world of frontend development by integrating Vue with my Laravel backend. To streamline my API calls and make them more organized for different models, I decided to create a separate file name ...

Set the array back to its initial value of 1 using jQuery and

After making substantial edits to this question, I find myself in need of a reset button for the code. The current item needs to be reset back to 1 so that I can use it again, but the issue lies in the fact that only the current item is reset while the hig ...

Access another page by clicking on a link within an HTML document

Is it possible to include an anchor tag in demo1.html that, when clicked, will take the user to the demo2.html page and automatically select a data filter on that page? Here is the code snippet for demo1.html: <li> <div><a href="urunli ...

What is the reason for handlers not being able to work without passing parameters in React?

I recently made a discovery but I'm still puzzled about how it works. In the past, when creating React components, I used to follow this pattern: class App extends React.Component { state = { input: '' } onChangeHandler = event = ...

Development and staging setups tailored specifically for a JavaScript SDK

Currently, I am working with a Javascript SDK that is available on NPM. Alongside this, I have a Vue application utilizing the SDK and it's crucial for me to test them together across various pre-production environments (such as staging). Here are the ...

Transform the Material UI grid orientation to horizontal row for content display

I'm just starting out with material UI and I've put together a grid that includes two components - an autocomplete and a button. Right now, they're stacked on top of each other, but I want to align them side by side in a row. Here's the ...

Node-express can seamlessly switch between multiple databases dynamically

After extensive searching for a solution to my problem, I have come up empty-handed. If anyone has experience in similar situations, your help would be greatly appreciated. I have developed an application server in Node Express with MySQL as the database. ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

What is the reason that when we assign `'initial'` as the value for `display` property, it does not function as intended for list elements?

To toggle the visibility of elements, I have created a unique function that accepts an object and a boolean. Depending on the boolean value, either 'none' or 'initial' is assigned to the 'display' property of the specified obj ...

Concealing and revealing template URLs with AngularJS

I am currently working with a dynamic Array in my Controller that contains templates (html files) structured similarly to the example below: $scope.templates = [ { name: 'template1.html', url: 'template1.html'}, { name: ...

Is it possible to automatically close navigation dropdowns when the screen size changes?

I am using a bootstrap 4 navbar with dropdowns that open with CSS animation/fade-in on desktop, and a separate toggle button for mobile. Everything works fine, but when I open the dropdowns on mobile and then resize the window screen, they remain open whic ...

The function `Object.entries().map()` in TypeScript does not retain the original data types. What changes can I make to my interface to ensure it works correctly, or is there a workaround

Working with this interface: export interface NPMPackage { name: string; description: string; 'dist-tags': { [tag: string]: string; }; versions: { [version: string]: { name: string; version: string; dependencie ...

Experiencing issues with the functionality of jQuery AJAX?

I am experiencing difficulties with a jQuery AJAX post. Here is the code: <script> var callback = function(data) { if (data['order_id']) { $.ajax({ type: 'POST', url: '<?php echo $_SERV ...

The combination of Heroku (Cedar) with Node, Express, and Jade is causing issues with the client-side javascript files in a subdirectory. While they work fine locally with foreman and

As a newcomer to node and Heroku, I am facing what seems like a simple permission issue. Despite my efforts, I am unable to pinpoint the exact source of the problem. In a sub-directory located one level beneath my root directory where the web.js file is s ...