Combining nested objects into a single object

Can a nested array object be flattened into a single object? In my query, I aim to eliminate the source object and combine all properties into one object (see the desired output below).

    var result = [
    {"_id":"12345",
    "_type":"feeds",
    "_source":{
              "title": "hi all solve it",
              "link": "www.face.com",
              "content": "Hi thewwewewedwe asdasdasdasd",
              "createdAt": "2018-08-08T11:42:40.073Z",
              "updatedAt": "2018-08-08T11:42:40.073Z",
              "reply": []
                }
    }]

 //desired output

     var newResult = [
        {
            "_id":"12345",
            "_type":"feeds",
            "title": "hi all solve it",
            "link": "www.face.com",
            "content": "Hi thewwewewedwe asdasdasdasd",
            "createdAt": "2018-08-08T11:42:40.073Z",
            "updatedAt": "2018-08-08T11:42:40.073Z",
            "reply": []
        }];

Answer №1

To handle this situation, you can utilize the spread syntax

var result = [{
  "_id":"12345",
  "_type":"feeds",
  "_source": {
    "title": "hi all solve it",
    "link": "www.face.com",
    "content": "Hi thewwewewedwe asdasdasdasd",
    "createdAt": "2018-08-08T11:42:40.073Z",
    "updatedAt": "2018-08-08T11:42:40.073Z",
    "reply": []
  }
}];
    

const { _source, ...rest } = result[0];

const flattenResult = [{
  ...rest,
  ..._source,
}];

console.log(flattenResult);

I'll leave it up to you to figure out the solution when dealing with a scenario where result.length is greater than 1.

Answer №2

Using basic JavaScript for a simple approach

Capable of handling multiple entries

var data = [{ "_id": "12345", "_type": "feeds", "_source": { "title": "hello everyone, please assist me", "link": "www.face.com", "content": "Hello all asdfasdfasdf", "createdAt": "2018-08-08T11:42:40.073Z", "updatedAt": "2018-08-08T11:42:40.073Z", "reply": [] } },{ "_id": "12346", "_type": "feeds", "_source": { "title": "hello everyone, please assist me", "link": "www.face.com", "content": "Hello all asdfasdfasdf", "createdAt": "2018-08-08T11:42:40.073Z", "updatedAt": "2018-08-08T11:42:40.073Z", "reply": [] } }]

data = data.map(function(entry) {
  var obj = entry._source;
  for (var prop in entry) {
    if (prop != "_source") obj[prop] = entry[prop];
  }
  return obj;
})
console.log(data)

Answer №3

One way to flatten an array of objects is to iterate through the array, then iterate through the keys of each object to extract the key names. If a key with the name "_source" is encountered, you can merge its content into a new flattened object using the method Object.assign(). This approach is applicable for arrays like "result" containing one or more objects.

var result = [{
  "_id": "12345",
  "_type": "feeds",
  "_source": {
    "title": "hi all solve it",
    "link": "www.face.com",
    "content": "Hi thewwewewedwe asdasdasdasd",
    "createdAt": "2018-08-08T11:42:40.073Z",
    "updatedAt": "2018-08-08T11:42:40.073Z",
    "reply": []
   }
},
{
  "_id": "1234567",
  "_type": "feeds123",
  "_source": {
    "title": "hi all solve it 123",
    "link": "www.face.com",
    "content": "Hi thewwewewedwe asdasdasdasd",
    "createdAt": "2018-08-08T11:42:40.073Z",
    "updatedAt": "2018-08-08T11:42:40.073Z",
    "reply": []
  }
}];
var newArray = [];
result.forEach(function(obj){
  var tempObj = {};
  Object.keys(obj).forEach(function(key){
    if(key !== '_source'){
      tempObj[key] = obj[key];
    } else {
      tempObj = Object.assign(tempObj,  obj[key]);
    }
  });
  newArray.push(tempObj);
});
console.log(newArray);

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

What is the correct way to invoke a function expression that is nested within another function?

Is it possible to call a function expression that is nested within another function in JavaScript? let x = function() { //perform some tasks let y = function() { console.log('Greetings Earthlings!') } } x(); ...

Issue with series of node commands getting stuck on npx command

I have a custom node script that I use to automate the setup of my application. This script creates directories, generates files, and executes a series of node commands. Everything functions correctly for the most part. The specific commands being executed ...

Tips for reducing the delay between pressing a button and starting an animation

Currently working on a hamburger menu with animations for displaying and hiding the menu after clicking a button. I'm facing an issue where there is a delay in hiding the menu equal to the animation time. Despite trying multiple solutions, the delay p ...

Ways to display an image for a duration of 3 seconds upon clicking each button

Need help with my HTML/js code. I have a button that should display an image when clicked, but it's not working properly. Here is the code snippet: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&qu ...

Refreshing data within a C array

Let's consider two tables, B and Y, each containing 3 elements. The goal is to update array Y with the values from array B, so that essentially B[i]=Y[i]. I have written the following code to achieve this. The expectation is that for i=0, it will retr ...

Automatically resizing images in a canvas when their resolution exceeds the canvas size in HTML5

I am currently using Html5, fabric.js, and JavaScript to upload multiple images to a canvas. However, there are instances where the uploaded image size exceeds that of the canvas. I am looking for a way to ensure that the image is set to a fixed size. v ...

The dropdown menu repeatedly opens the initial menu only

My script fetches data from a database to populate a table with one row for each member. Each row contains a dropdown list with the same class and ID. Although I attempted to open and close the dropdowns using specific codes, I am facing an issue where onl ...

What is the best way to utilize regex patterns in order to divide a string into segments of numbers, specific words, and separate characters unless they combine to form a certain phrase?

Can someone help me figure out how to split a String into specific sections using regex? I want the output to look like this: input: "3.0catsdogs}qd7cats8.0dogs" //specified strings: "cats", "dogs" output[]: ["3.0", ...

Can anyone recommend any quality libraries for uploading files in Silverlight or HTML that also support metadata?

I am in the process of developing a solution within SharePoint 2010 that allows for the upload of multiple documents while also tagging them with metadata. Is there anyone familiar with an innovative file-upload control or solution that enables the additi ...

Is there a conflict between bootstrap.min.JS and chart.min.js?

I have been working on developing an admin page for customer support and I recently added a visually appealing chart to display some data on the home screen. The chart integration was successful, but when I introduced tab panes to the page and refreshed ...

Determine in a JSON array and add to an array object if the key is not found

I've got a JSON array like this: 0: {Id: "1", name: "Adam", Address: "123", userId: "i98"} 1: {Id: "2", name: "John", Address: "456"} The second object in the array doesn't have a userId key. How can I iterate through the array and add the ...

Get Fit with Dynamic Programming

Currently delving into the realm of reactive programming using RxJS, I encountered the following exercise: Initialization of an empty array Upon application launch, a new Date() is added to the array Each mouse click appends a new value to the array alon ...

Determining the presence of an object within an array of objects in Angular

I am currently working with Angular 8 and I need to check if an object exists within an array of objects. Here is the object I want to check for: let objVenIns = { 'CntNumber': 4, 'CntMixer': 2, ...

Storing image visibility using a cookie or checkbox in Javascript

Hello, I'm new to Javascript and just started experimenting with building a simple web app. I have some experience with Python, so I wanted to see how easily I could translate my skills into Javascript. The app I'm working on is meant to help us ...

What is the process to retrieve a function from a router javascript file using node.js?

Dealing with a web application that is not my own, I now have the task of sending out one hundred emails. Unfortunately, the code is poorly documented and written, which means I need to test it to figure out what I can and cannot do. However, I'm uns ...

How do you update the icon for a webpage in HTML?

I'm looking to update the icon on a button when it is clicked. It would be helpful to know if I can also add an animation to the icon after the button click. ...

Grouping data values in an array using PHP

Here is the $data variable content: cv = 1,2,3,4,5:::cpt = 4,5 ... I am looking for a function that can take a number as a parameter (the number will be the value from $data). For example: function getPermission($id) { ... return $something; } If I ...

the button function is unresponsive

Can someone please help me troubleshoot my jQuery code? Everything seems fine, but the generate button is not working when clicked! PS: I've searched extensively for a solution to this problem but haven't been able to find one. I've also at ...

Discovering the highest value in MongoDB

Good Morning! I am currently working with a MongoDB structure that looks like this: { "_id": 19, "name": "Fredia Donan", "faculty": "Zoomzone", "lectures": [ { &qu ...

Incorporate communication between the front-end and backend

I encountered an error while attempting to import the getUser function in my backend code. The actual function is located in the frontend at ../utils/auth. How can I successfully import between front-end and backend? Or might there be another issue at pla ...