Transform object into an array by flattening it

I'm currently working on a task where I have an object that needs to be transformed into an array with the property as the key. The structure of the object is as follows:

{
 Cat: {
   value: 50
 },
 Dog: {
   value: 80
 }
} 

The desired output should look like this:

[
 {
    animal: 'Cat',
    value: 50
 },
 {
    animal: 'Dog',
    value: 80
 }
]

If anyone can provide assistance, it would be greatly appreciated.

So far, I've attempted:

 const animalArr = Object.entries(AnimalObj);

However, I am unsure about what steps to take next.

Answer №1

const AnimalObj = {
  Cat: {
    value: 50
  },
  Dog: {
    value: 80
  }
};

const result = Object.entries(AnimalObj)
  .map(([animal, { value }]) => ({ animal, value }));

console.log(result);

Loop through all the elements within AnimalObj using Object.entries and create a new object for each entry using map.


The part involving the map function in this answer may appear complex.

([animal, { value }]) => ({ animal, value })

This actually consists of two parts:

  • Destructuring of arguments

    When using Object.entries, we receive an array containing keys and their corresponding values as arrays. For example,

    console.log(Object.entries(AnimalObj))
    would output

    [ [ 'Cat', { value: 50 } ], [ 'Dog', { value: 80 } ] ]
    

    We then take each individual array passed to map and use [animal, { value }] to extract the first string into the variable animal, while destructuring the second element (an object) to retrieve only the value.

  • Creation of objects

    With all the necessary pieces obtained - animal and value, we utilize shorthand notation to form objects with { animal, value }. This results in an object with keys animal and value, each holding the corresponding variable's value.

Answer №2

const animals = {
 Tiger: {
   count: 70
 },
 Lion: {
   count: 90
 }
};

const result = Object.entries(animals).map(([type, info]) => {
  return {
    species: type,
    ...info
  };
});

console.log(result);

Answer №3

If you need to transform an object into an array of key-value pairs, you can use the Object.entries method along with the map function to achieve the desired output.

const 
  dataObj = { Cat: { value: 50 }, Dog: { value: 80 } },
  dataArr = Object.entries(dataObj).map(([animal, { value }]) => ({ animal, value }));

console.log(dataArr);

Answer №4

To start, utilize the Object.entries() method to transform the key-value pairs within the object into an array. Afterwards, employ destructuring with the Array#map method in the following manner:

const data = { Apple: {quantity: 10 },Banana: { quantity: 20 } };

const result = Object.entries( data )
.map(([item, details]) => ({item, ...details}));

console.log( result );

Answer №5

There's no need for an extra flattening step - you can simply map it directly like this:

AnimalObject = {
 Lion: {
   count: 30
 },
 Tiger: {
   count: 60
 }
} 


 const animalList = Object.entries(AnimalObject).map(([ name, info ]) => ({ animalType: name, count: info.count }));
 console.log(animalList)

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

Instructions on calling a function with AngularJS ng-click in a template rendered by a Grails controller

Is there a way to invoke a function using angularjs ng-click on a template that is rendered from a grails controller? I have tried, but the jQuery function call seems to work fine while the ng-click() function does not. What am I missing here? I'm rea ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

Bootstrap / Blazor - no action when clicking on an image link

Having issues with adding a simple HTML link around an image in my Bootstrap 4.5 / Blazor app. When I click on the link, nothing happens. How is this possible? I've tried using the <a href"..."><img ...> pattern, as well as NavL ...

Mocking a Promise-returning dependency for a React Component in Jest

There's a React component I'm working on that has a dependency like so: import { fetchUsers } from '../../api/'; This function is a utility that returns a Promise. My challenge lies in trying to mock this dependency using Jest. I&apo ...

Guide on linking draggable elements

Currently, I have a set of div elements that I am able to clone and drag and drop into a specific area. Now, I am looking for a way to connect these divs with lines so that when I move the divs, the lines will also move accordingly. It's similar to cr ...

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...

What is the best way to convert an array of JSON objects into a two-dimensional array in Java using GSON?

I have a JSON string that looks like this: [{ "id": 3, "city": "Ilmenau", "floor": null, "housenumber": "35", "streetname": "Blumenstraße", "zip": "98693" }, { "id": 4, "city": "Berlin", "floor": null, "housenumber ...

React component's useEffect runs twice when missing dependencies

Hi there, I'm currently facing an issue with the useEffect hook in my code. I have set it without any dependencies because I only want it to run once. The problem arises when the useEffect in the Profiles.js component runs twice, even though I am usin ...

Transferring ExpressJS API scripts to the Server for Deployment

After developing a basic API with ExpressJS to interact with MongoDB for CRUD operations, I successfully ran it locally using the command "npm nodemon" in the source folder. Testing it with Postman confirmed its functionality. Now, my concern is how to dep ...

I am looking to retrieve information from mongodb and then transform it into a JSON object using node.js. Can you guide

I am on a mission to retrieve data from a MongoDB database and transform it into a JSON object in Node.js. The goal is to be able to easily manipulate this data as if it were a simple JSON object. Here's the current code snippet I'm working with: ...

How can you effectively use asynchronous functions?

I'm currently exploring Express and asynchronous/functional programming. app.get('/users/:id', (req, res) => { let id = req.params.id; let User = require('../models/user') User.is_complete(id, (validate) => { conso ...

What is the best way to implement filtering on a click event in React Three.js?

I recently explored a 2 cubes sample, and I encountered an issue. When clicking on one cube, both it and the cube behind it get clicked at the same time. Is there a way to make sure that only the nearest cube is clicked or hovered? In simpler terms, when ...

Troubleshooting the NullInjectorError in Angular - Service Provider Missing?

I'm facing an issue in my code where I have buttons that should trigger pop-ups displaying details as a list when clicked. However, every time I click the buttons, I encounter the error mentioned below. It seems like I am unable to access the desired ...

What is the best way to create a repetitive pattern using a for loop in Javascript?

I want to create a repeating pattern to color the background, but once i exceeds colors.length, the background color stops changing because, for example, colors[3] does not exist. I need colors[i] to start back at 0 until the first loop is complete. cons ...

Mastering the Art of Sending Multiple Values via Ajax

I'm having trouble passing multiple values using ajax in my code snippet. Here is the code I am working with: $(".ajax-button").change(function(event){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': '{{ ...

Navigating pinch to zoom: Strategies for managing varying page locations

I've been using a combination of JS and CSS to position images within the viewport in a way that allows them to scale and translate accurately to fill the space. For the most part, this method works smoothly and is also able to handle browser zoom fu ...

Organizing information in local storage using an array and converting it to a string

After storing user inputs (Worker's name, Car Vin, Start time and End time) in the local storage, you want to sort the employees' names in alphabetical order. The question is where should the code be placed and how should it be written? // Car C ...

how can one exhibit the value of an object in TypeScript

Does anyone know how to properly display object values in forms using Angular? I can see the object and its values fine in the browser developer tools, but I'm having trouble populating the form with these values. In my *.ts file: console.log(this.pr ...

What is preventing typescript from inferring these linked types automatically?

Consider the following code snippet: const foo = (flag: boolean) => { if (flag) { return { success: true, data: { name: "John", age: 40 } } } return { success: false, data: null } ...

What is the best way to apply CSS styles to a child div element in Next.js?

I'm currently working on enhancing the menu bar for a website project. Utilizing nextjs for my application I am aiming to customize the look of the anchor tag, however, encountering some issues with it not rendering correctly. Here is a snippet of ...