What is the best way to collapse an array within an object?

I'm looking for a way to flatten an array within an object using JavaScript, preferably ES6. I'm not sure if "flattening" is the correct term here, but I just want a solution to achieve this transformation.

Currently, I have this structure:

{
  id: "123",
  name: "test",
  history: [
    {
      id: "456",
      name: "test2"
    },
    {
      id: "789",
      name: "test3"
    }
  ]
}

And I want to convert it to:

{
  id: "123",
  name: "test"
},
{
  id: "456",
  name: "test2"
},
{
  id: "789",
  name: "test3"
}

The original object includes a "history" property specific to that object. Any suggestions on how to approach this?

Answer №1

To efficiently separate history and the first object, you can utilize destructuring along with rest syntax. Afterwards, merge them into a single array using spread or concat methods.

const { history, ...obj1 } = {"id":"123","name":"test","history":[{"id":"456","name":"test2"},{"id":"789","name":"test3"}]}

const result = [obj1, ...history]

console.log(result)

Answer №2

give this a shot:

 let dataObj =  {
  "id": "123",
  "name": "example",
  "log": [
    {
      "id": "456",
      "name": "example2"
    },
    {
      "id": "789",
      "name": "example3"
    }
  ]
}

const  {id, name, log} =  dataObj;
const finalArr  = [{id, name} , ...log];

console.log(finalArr);

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

How can we efficiently add a new node to a polyline link in gojs while maintaining the original positions of points in the links adjacent to the inserted node

After posting a question on StackOverflow (Seeking Javascript library for displaying and editing networks of nodes and edges), I was directed to the gojs splice sample. The sample has been helpful, but I've hit a roadblock trying to achieve the speci ...

The image will only display upon receiving a link, not a path

Having some trouble displaying an image on my website, despite having successfully done so in the past for other projects. The image is located in the same folder as my HTML file. Here's what I've tried: <img src="reddit.png"/> <img s ...

Develop an "Import Interface" using TypeScript

I have a large project with many files and I believe using an import object would be beneficial. For instance, consider having menu.ts at the top level that every program will refer to: import router from "./router/index"; import controllers from ...

Utilizing jQuery to extract the value of a selected list item on click

I have been working on creating a list of items from JSON data and am facing an issue with retrieving the 'data-value' attribute of the clicked item. Here is my current code: const target = $('#list'); target.empty(); for (let i = 0 ...

Why does serializing a JavaScript Object to JSON result in "{}"?

Hello fellow developers, I'm currently working on setting up a LocalStorage feature for my web application. One issue I've come across is that all objects in the Model abstraction layer need to be serialized. I understand that functions aren&a ...

Extract branch, path, and URL from the .gitmodules file by utilizing JavaScript Regex

Is there a way to extract branch, path, and URL details from the .gitmodules file using JavaScript Regex? .gitmodules [submodule "PATH"] path = <PATH> url = <URL> [submodule "PATH"] path = <PATH> url = <URL> ...

JavaScript and .NET Core: Implementing file uploads without the use of FormData or FromFrom

Currently attempting to create a "basic" file upload feature. Utilizing JavaScript on the frontend and .NET Core on the backend. Previously, I had successfully implemented FormData / multipart, FromForm, and iFormFile. However, I have been advised agains ...

Using jQuery to initiate a page load into a new page within the WorkLight platform

I need help redirecting to a new page when the current page is loaded. My website is built using jQuery mobile in combination with WorkLight. Index.html: <body> <div data-role="importpages" id="pageport"> </div> </body> ...

Showing particular PHP array retrieved from MySQL

Currently, all columns from the MySQL result are being converted to JSON and displayed on the screen. However, I am interested in only printing two specific columns - $row['name'] and $row['gender']. Any suggestions on how to achieve th ...

Struggling to create a regular expression for a particular scenario

I'm dealing with nodes and currently faced with the task of applying a UNIX-like grep command to filter out specific content from an HTTP GET response. Below is the raw text received as the body variable: <?xml version="1.0" encoding="UTF-8" stand ...

I am curious about how to implement overflow:hidden along with position:sticky in React.js

My attempt to address the white space issue caused by a navbar I created led me to try using overflow:hidden. The navbar is generated using the Header component, and I desired for it to have a position: sticky attribute. However, I realized that I cannot ...

If the span id includes PHP data that contains a certain phrase

Hey there, it's my first time posting and I'm in a bit of a bind with this script... Let me give you some background information first I am trying to create a click function for a register button that will check the span id (e.g. $("#username_r ...

Is there a way to integrate Javascript code with a React component?

I need to find a way to include this block of code in just one specific React component. Any suggestions? <!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. --> <button sty ...

Can AngularJS Filters be used to convert a number into a string, but not the other way around?

After researching Angular JS filters, I discovered that the number filter is used to format a number as a string. However, there doesn't seem to be a built-in filter for converting a string to a number. In an attempt to solve this issue, here is so ...

Transforming my asynchronous code into a synchronous flow using setTimeout. Should I consider implementing promises?

I have a project in which I am creating a data scraper for a specific website. To ensure that I make a request only every 10 seconds, I have set up a setTimeout loop. This loop takes a URL as a parameter from an array of URLs that I manually input. In the ...

Menu options are unresponsive to clicks in the dropdown

Need help fixing my dropdown menu issue. Whenever I hover over the dropdown, it disappears before I can click on any items. Here is a snippet of the code causing the problem: #navContainer { margin: 0; padding: 0; padding-top: 17px; width: 220 ...

The concept of setting a value is not defined in JavaScript when compared to

Within my primary python script, the following code snippet is present. @app.route('/accounts/test/learn/medium') def medium(): word = random.choice(os.listdir("characters/")) return render_template('accounts/test/medium.html', word=w ...

Exploring the beauty of Node.js/Express.js with Chunked GET Requests

My current challenge involves making a GET request on a Node.js/Express.js backend that includes 80KB of data. The issue arises because the IoT board I am using for this request has a limited RAM of only 32KB, causing lag when trying to parse such a larg ...

Masonry ajax loading is not functioning properly

My images are supposed to load via ajax, but I am experiencing some issues. Sometimes it works perfectly fine, but most of the time they overlap each other like in this example. Where did I go wrong? Once I figure this out, I'll be able to refactor my ...

What are the steps for sorting objects in an array by their data type attribute?

I am currently working with a JavaScript array of people objects that is dynamically rendered from JS. My goal is to implement a filter on the objects based on the selection made in the dropdown menu and matching it with the department attribute specified ...