Combining JSON objects within an array

I'm working with a JSON Array that looks like this:

[
{"Name" : "Arrow",
"Year" : "2001"
},

{"Name" : "Arrow",
"Type" : "Action-Drama"
},
{ "Name" : "GOT",
"Type" : "Action-Drama"
}
]

and I want to convert it to look like this:

[
  { 
    "Name" : "Arrow",
    "Year" : "2001",
    "Type" : "Action-Drama",
  },
  {
   "Name" : "GOT",
   "Type" : "Action-Drama"
  }
]

If anyone can help me with this, I would greatly appreciate it.

Thanks in advance.

Answer №1

If you want to manipulate the data using JavaScript, you can utilize the Array#reduce method.

let collection = [{
    "Name": "Arrow",
    "Year": "2001"
  },
  {
    "Name": "Arrow",
    "Type": "Action-Drama"
  },
  {
    "Name": "GOT",
    "Type": "Action-Drama"
  }
]

let result = collection.reduce((obj, { Name, ...rest }) => {
  obj[Name] = obj[Name] || { Name };
  Object.assign(obj[Name], rest);
  return obj;
}, {})

console.log(Object.values(result))


Alternatively, you can achieve the same outcome using a traditional for loop along with an additional object to keep track of elements based on their Name.

let list = [{
    "Name": "Arrow",
    "Year": "2001"
  },
  {
    "Name": "Arrow",
    "Type": "Action-Drama"
  },
  {
    "Name": "GOT",
    "Type": "Action-Drama"
  }
]

let results = [],
  reference = {};

for (let i = 0; i < list.length; i++) {
  if (!(list[i].Name in reference)) results.push(reference[list[i].Name] = {});
  Object.assign(reference[list[i].Name], list[i]);
}

console.log(Object.values(results))

Answer №2

To efficiently manipulate data, you can utilize the reduce() and findIndex() methods.

let information = [
{"Title" : "Arrow",
"Released" : "2001"
},

{"Title" : "Arrow",
"Genre" : "Action-Drama"
},
{ "Title" : "GOT",
"Genre" : "Action-Drama"
}
]


let result = information.reduce((accumulator, current) => {
  let index = accumulator.findIndex(x => x.Title === current.Title);
  index === -1 ? accumulator.push({...current}) : accumulator[index] = {...accumulator[index],...current};
  return accumulator;


},[])
console.log(result)

Answer №3

Utilize the combination of reduce and Object.assign to merge the elements within the given array:

const values = [{
  "Name" : "Arrow",
  "Year" : "2001"
}, {
  "Name" : "Arrow",
  "Type" : "Action-Drama"
}, {
  "Name" : "GOT",
  "Type" : "Action-Drama"
}];

function mergeByProperty (property, elements) {
  return elements.reduce((accumulator, element) => {
    if (!accumulator[element[property]]) {
      accumulator[element[property]] = element;
    } else {
      accumulator[element[property]] = Object.assign(accumulator[element[property]], element);
    }
    return accumulator;
  }, {});
}

function objectToArray (object) {
  return Object.keys(object).map(key => object[key]);
}

console.log(objectToArray(mergeByProperty('Name', values)));

Answer №4

Check out this solution:

var obj1 = {
  apple: 0,
  banana: { weight: 52, price: 100 },
  cherry: 97
};
var obj2 = {
  banana: { price: 200 },
  durian: 100
};

// Combine obj2 with obj1, recursively
$.extend( true, obj1, obj2 );

console.log( JSON.stringify( obj1 ) );

Reference:

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

The issue with the value of the textarea in Selenium automated tests using

I have a webpage with Javascript where I've implemented a textarea using the following code: var textarea = $("<textarea>"); textarea.change(() => { console.log(textarea.val()); }); When I update the value in the textarea and then chang ...

Managing multiple Socket.io connections upon page reload

I am currently developing a real-time application and utilizing Socket.io for its functionality. At the moment, my setup involves receiving user-posted messages through the socket server, saving this data to a MySQL database via the controller, and then b ...

Jasmine and Karma encountered a TypeError stating that the function this.role.toLowerCase is not valid

Currently, I am in the process of writing a test case for a page within an application that our team is actively developing. However, I have encountered a challenging error within one of the test cases that I am struggling to overcome. Below is my Spec fil ...

What could be causing certain javascript functions to not work properly?

Currently, I am using JavaScript and AJAX to validate a registration form. The functions restrict(elem) and checkusername() are both working as intended. When the AJAX passes the checkusername variable to PHP, it checks if the username exists and displays ...

The Electron BrowserWindow turns dark post execution of the .show() method

Revision: After some tinkering, I discovered that the issue was related to the order in which I created the windows. Previously, my code looked like this: app.whenReady().then(() => { createWindow(); spawnLoadingBlockWindow(); spawnGenerati ...

Decoding a Json list with angularJS

I have a JSON dataset structured as follows: $scope.jsondata = [{filename:"/home/username/textfiles/0101907.txt"},{filename:"/home/username/textfiles/0124757.txt"},{filename:"/home/username/textfiles/0747332.txt"} ... ]; Here is my HTML code: <li ng ...

using the information from the child array within a v-if condition

I'm struggling to extract data from a child array and utilize it in my v-if condition. Below are my data and code. Any assistance would be appreciated, even if it's just pointers to the right documentation. <div class='post' v-for= ...

Typescript is failing to compile classes in a reliable sequential order

In my MVC 5 project, I am using TypeScript and angular. There are three TS files: Controller1.ts, Controller2.ts, and app.ts. The issue arises when I compile the program for the first time - everything usually compiles correctly in the expected order. Howe ...

Error encountered when trying to send form data through an AJAX request

Whenever a user updates their profile picture, I need to initiate an ajax call. The ajax call is functioning properly, but the issue lies in nothing being sent to the server. <form action="#" enctype='multipart/form-data' id="avatar-upload-fo ...

Events related to key press timing in HTML 5 canvas

Currently, I am developing a game similar to Stick Hero for Android using HTML5. I am working on the code that will capture the time of key press (specifically the right arrow key with ASCII 39) in JavaScript and expand a stick accordingly. <!doctype h ...

Encountering vulnerabilities during NPM installation, attempting to fix with 'npm audit fix' but unsuccessful

While working on my react project, I decided to incorporate react-icons by running npm install react-icons in the command prompt. However, after some time, the process resulted in the following errors: F:\Areebs\React JS\areeburrub>npm in ...

Ways to extract data from a chosen radio button choice

Excuse me, I have a form with an input field and radio buttons. Can someone please help me with how to retrieve the value of the selected radio button and then populate that value into the input text field? For reference, here is the link to the jsfiddle: ...

Exploring the world of npm packages: from publishing to utilizing them

Exploring My Module npmpublicrepo -- package.json -- test.js The contents of package.json are as follows: { "name": "npmpublicrepo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Erro ...

It appears that the JavaScript array is able to modify itself autonomously

Currently, I am working on a project using P5.js where I am saving values in an array and then creating a copy of that array to manipulate. However, I have encountered an issue where manipulating the second array also changes the original one, and I cannot ...

When additional lines are drawn elsewhere on the HTML5 Canvas, the diagonal lines will gradually appear thicker and more pronounced

For horizontal and vertical lines, using a translation of 0.5 for odd stroke widths results in crisper and sharper lines. But what about diagonal lines? Link to jsfiddle <!DOCTYPE html> <html lang="en"> <body style="background: black"& ...

Express js is failing to deliver static assets

Hello, I'm having an issue with Express Js. It seems like a beginner problem - static files are not being served properly. const express = require('express'); express() .set('view engine','ejs') .use(express.stat ...

There are a few steps to take in order to sort an array of objects by a

I want to organize and display data in a sortable table format javascript let dataList = [ { idx: number, name: string, btn: number, index: number }, { idx: number, name: string, btn: number, index: number }, { idx: number, name: string, btn: number ...

Ordering BufferGeometries in Three.js for Accurate Rendering

After consulting the discussion on the previous inquiry, I have been working on constructing models in BufferGeometry and have come to understand that the transparent flag plays a role in the rendering order: objects with transparent materials will be rend ...

Having trouble updating the input value in AngularJS?

As I venture into customizing an AngularJS tutorial on a Saturn Quiz, I am transforming it from multiple choice to a fill-in-the-blank quiz. The challenge I face is that the first answer registers as correct or incorrect, but subsequent questions always s ...

What is the best way to pass or declare elements of an array in C language?

After creating a program designed to process specific elements from an array of double purchase within a function, I encountered an issue when trying to call the function in my main code: float beverages () { char response; double purc ...