Eliminating repeated keys from an array of objects

I'm dealing with an array of objects that looks like this

let array = [
  {
    sector: "adad"
  },
  {
    sector: "adadasdsd"
  },
  {
    sector: "sdsdsd"
  },
  {
    origin: "sdfsf"
  },
  {
    destination: "dfsfsdf"
  }
];

My goal is to transform it into this format:

let array = [
  { sector: ["adad", "adadasdsd", "sdsdsd"] },
  { origin: ["sdfsf"] },
  { destination: ["dfsfsdf"] }
];

I believe using the reduce method is the way to go here, but I'm struggling with the implementation. Any guidance on how to achieve this transformation?

Answer №1

To efficiently store values with the same keys and then map them to single key/value pairs, consider using a hash table with a mapping function.

let array = [{ sector: "adad" }, { sector: "adadasdsd" }, { sector: "sdsdsd" }, { origin: "sdfsf" }, { destination: "dfsfsdf" }],
    grouped = Object
        .entries(array.reduce(
            (result, obj) => (
                Object.entries(obj).forEach(([key, value]) => (result[key] = result[key] || []).push(value)),
                result
            ),
            Object.create(null)
        ))
        .map(([key, value]) => ({ [key]: value }));
   
console.log(grouped);

Answer №2

One possible solution involves utilizing the jQuery library.

let newArrays = {
        category: [],
        start: [],
        end: []
    }


$.each(existingArray, function (_index, item) {
    if (item.category != null)
        newArrays.category.push(item.category)
    if (item.start != null)
        newArrays.start.push(item.start)
    if (item.end != null)
        newArrays.end.push(item.end)
})

Answer №3

Using the Vanilla solution along with reduce function:

let data =   [
  {
    "type": "apple"
  },
  {
    "type": "banana"
  },
  {
    "type": "orange"
  },
  {
    "color": "red"
  },
  {
    "size": "large"
  }
]

let organized = data.reduce((acc, entry) => {
  if (entry.type) { acc[0].type.push(entry.type); }
  else if (entry.color) { acc[1].color.push(entry.color); }
  else { acc[2].size.push(entry.size); }
  return acc;
}, [{type: []}, {color: []}, {size: []}]);

console.log(organized);

Answer №4

Here is a simple solution incorporating the Array.prototype.reduce() method:

let data = [{"type": "apple"},{"type": "banana"},{"type": "orange"},{"category": "fruit"},{"category": "vegetable"}]

let transformedData = data.reduce((accumulator, currentValue, index) => {
  let key = Object.keys(currentValue)[0];
  if (!(key in accumulator)) accumulator[key] = [];
  if (!accumulator[key].includes(currentValue[key])) accumulator[key].push(currentValue[key]);
  return accumulator;
}, {})

console.log(transformedData)

Answer №5

Check out this approach:

const data =   [
  {
    "fruit": "apple"
  },
  {
    "fruit": "banana"
  },
  {
    "vegetable": "carrot"
  },
  {
    "fruit": "orange"
  },
  {
    "vegetable": "lettuce"
  }
]

let result = [];
data.map(item=>{
  let key = Object.keys(item)[0], value = item[key],
      objResult = result.filter(r=>r[key]);  
  if (objResult.length == 0) {
      let obj = {};
      obj[key] = [value];
      result.push(obj);
  } else 
      objResult[0][key].push(value);
});

console.log(result);

Answer №6

If you employ the combination of Array.reduce and Map as the accumulator, you can efficiently tackle this problem with brevity:

let data = [{ name: "John" }, { name: "Jane" }, { age: 25 }, { gender: "Male" }, { city: "New York" } ];

const result = data.reduce((accumulator, currentValue, index, array) => {
  Object.keys(currentValue).forEach(key => accumulator.set(key, [...(accumulator.get(key)||[]), currentValue[key]]))
  return index == array.length - 1 ? Array.from(accumulator, ([k,v]) => ({[k]: v})) : accumulator
}, new Map())

console.log(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

I am struggling with clicking on Bootstrap's pagination using AngularJS

I'm still getting the hang of Angularjs. I managed to set up a pagination system, but for some reason, I can't seem to interact with it when I run my project. Take a look at this screenshot that illustrates my issue: https://drive.google.com/fil ...

Are you unsure whether to use Ajax or jQuery? If you need assistance in adding parameters to

Currently delving into ajax/jQuery and encountering some hiccups. Here's the code snippet: .click(function() { var period = 'ALL'; if ($('#registerat input:checked').val() != 'ALL') period = ...

ASP.NET Dynamic Slideshow with Horizontal Reel Scrolling for Stunning

I'm curious if there is anyone who can guide me on creating a fascinating horizontal reel scroll slideshow using asp.net, similar to the one showcased in this mesmerizing link! Check out this Live Demo for a captivating horizontal slide show designed ...

Locate a jquery element that is within a parent element containing specific text

This is the format I currently have: <td width="270px"> <img class="bullet" border="0" valign="top" src="gray-bullet.gif"> this is the text </td> Can someone provide me with a query to specifically target the img element with the class ...

Showing nested routes component information - Angular

I am working on a project that includes the following components: TodosComponent (path: './todos/'): displaying <p>TODO WORKS</p> AddTodosComponent (path: './todos/add'): showing <p>ADD TODO WORKS</p> DeleteTo ...

What could be the reason for the "begin" script failing to execute?

I have a simple node and express application that works as expected, but I encounter an issue when trying to run the server from the script. When my script is set to "start", running the command simply opens my cmd. However, if my script is set to any oth ...

What is the best way to initiate a change event using JavaScript?

I am attempting to enable my 4th checkbox automatically when there is a new value in the textbox (myinput). If the textbox is empty, I want to disable it. Currently, you have to tab out before the change event is triggered. Also, how can I check for an e ...

Ember - Issue with Page Display

Currently tackling my first ember application, which consists of two pages: the Welcome page and a page displaying student details. To accomplish this, I have established two routes named index and studentdb. Unfortunately, I'm encountering an issue w ...

Leveraging Expressjs to act as a proxy for handling cross-origin requests made via AJAX

I'm working on a website that relies entirely on external APIs, without any server-side logic. All data will be retrieved from an external API. The backend server is mainly used for asset management and routing. We've decided to use nodejs with e ...

Tips for creating nested maps of an array without triggering the key prop warning

I am dealing with an array of data: const arr = [ { title: "title1", content: [ { id: "home", name: "Home", }, { id: "services", name: "services", ...

The context of the selector causes an error to be thrown

Why does jQuery throw an exception when I attempt to select an element with context? The code is as follows: jQuery('b', "DAS<br/><br/><b>ID</b> = 02<br/><b>NAMA DAS</b> = CITARUM<br/><b>LUAS ...

Issue with Titanium: Unable to scroll within tableview

The tableview is not scrolling as expected. I tested it on a mobile device and the scrolling worked fine, but it doesn't seem to work on tablets. Please assist. CODE var win = Titanium.UI.createWindow({ title : 'Medall app', back ...

Using Jquery's $.each() method within an ajax call can be a powerful

Is it possible for a jQuery each loop to wait for Ajax success before continuing when sending SMS to recipients from an object? I want my script to effectively send one SMS, display a success message on the DOM, and then proceed with the next recipient. O ...

Passing values to the next page is not functioning as expected

I'm having trouble passing a variable called userId to the next page in my application. Below is the snippet of code I am using to pass the value to the next page: $.each($.parseJSON(data), function(key, value) { var userId = value.id_user; ...

Module for Node.js that handles .ini files where variable names can begin with a number

.ini file: [1] 10X=true [2] 10X=true node.js : var mS = ini.parse(fs.readFileSync(__dirname + '/XXX/MS.ini', 'utf-8')); console.log(mS.1.10X); I am utilizing the ini module in node.js, which can be found at this link: https://www.n ...

identify when the React component has reached the bottom of the element by reading the

Is there a way to access the scroll handler's event without being able to access offsetTop, scrollTop, etc? class App extends React.Component { handleScroll = e => { console.log(e.target.scrollTop); }; componentDidMo ...

Text area featuring unique border design, with border color change upon focus?

Currently, I have a text area with borders that are designed in a unique way. However, I am looking to change the border color when the user focuses on the text area. Do you have any suggestions on how I can achieve this effect without affecting the curre ...

DxDataGrid: Implementing a comprehensive validation system for multiple edit fields

I'm currently working with a DxDataGrid within an Angular Application. Within this particular application, I have the need to input four dates. I've implemented validation rules that work well for each individual field. However, my challenge aris ...

Insert a JSX element into the body of a webpage using React JSX

Is there a way to dynamically add elements to the end of the body using vanilla JavaScript? const newRecipe = <div id = "container"> <div className="recipe App" id="four" onClick={this.toggleRecipeList.bind(this)}>{this.state.recipeName} < ...

Type in "Date" and select a date using your mobile device

Hey, does anyone know a good solution for adding placeholder text to an input with type="date"? I'm looking for a way to utilize the phone's built-in date selection feature on a website, rather than having users manually enter dates using the ke ...